一对多资源关系返回空

时间:2018-07-05 10:21:05

标签: laravel eloquent

我正在尝试使用Laravels API资源类返回关系。每个订单有很多订单总数。

我的订单模型

namespace App;

use Illuminate\Database\Eloquent\Model;

class Orders extends Model
{
    protected $table = 'zen_orders';

    public function ordersTotals() {
        return $this->hasMany(OrdersTotalsModel::class, 'orders_id');
    }
}

我的订单资源

namespace App\Http\Resources;

use Illuminate\Http\Resources\Json\Resource;

class OrdersResource extends Resource
{
    /**
     * Transform the resource into an array.
     *
     * @param  \Illuminate\Http\Request  $request
     * @return array
     */
    public function toArray($request)
    {
        return [
            'id' => $this->orders_id,
            'customername' => $this->customers_name,
            'paymentmethod' => $this->payment_method,
            'datePurchased' => $this->date_purchased,
            'status' => $this->orders_status,
            'currency' => $this->currency,
            'orderTotal' => $this->order_total,
            'ordersTotals' => new OrdersTotalsResource($this->id),
        ];
    }
}

我的订单总数模型

namespace App;

use Illuminate\Database\Eloquent\Model;

class OrdersTotalsModel extends Model
{
    protected $table = 'zen_orders_total';
    protected $primaryKey = 'orders_total_id';

    public function ordersTotals() {
        return $this->belongsTo(Orders::class, 'orders_id');
    }
}

我的订单总资源

namespace App\Http\Resources;

use Illuminate\Http\Resources\Json\ResourceCollection;

class OrdersTotalsResource extends ResourceCollection
{
    /**
     * Transform the resource into an array.
     *
     * @param  \Illuminate\Http\Request  $request
     * @return array
     */
    public function toArray($request)
    {
        return [
            'id' => $this->id,
            'type' => $this->title,
            'amount' => $this->value,
          ];
    }
}

我目前通过提供的代码遇到此错误:

Symfony\Component\Debug\Exception\FatalThrowableError: Call to a member function toBase() on null in file

在此错误之前,我只会得到此消息:

{
    "id": 389331,
    "customername": "John Smith",
    "paymentmethod": "Credit/Debit Card",
    "datePurchased": "2017-01-01 00:11:28",
    "status": 3,
    "currency": "GBP",
    "orderTotal": "36.99",
    "ordersTotals": []
}, 

我已尽可能地遵循文档并尝试了此处演示的所有可能方法,我相信不会调用“订单总数”模型,因为我对模型和资源所做的任何更改都不会产生影响。

1 个答案:

答案 0 :(得分:0)

我的方法是错误的,对于将来的访问者,我试图使用一种资源从关系中检索记录。

订单资源上,我添加了:

'ordersTotals' => OrdersTotalsResource::collection(
OrdersTotalsModel::where('orders_id', '=' , $this->orders_id)
->orderBy('sort_order')
->get()
),

我在错误地查询模型,并且混淆了我的主键。

我使用这种调试方法来帮助诊断我要去哪里。

namespace App\Providers;

use Illuminate\Support\ServiceProvider;
use Illuminate\Support\Facades\App;
use Illuminate\Support\Facades\Event;
use Illuminate\Support\Facades\Log;

class AppServiceProvider extends ServiceProvider
{
    /**
     * Bootstrap any application services.
     *
     * @return void
     */
    public function boot()
    {
        //
    }

    /**
     * Register any application services.
     *
     * @return void
     */
    public function register()
    {
        if (env('APP_DEBUG') == true) {
            Event::listen('Illuminate\Database\Events\QueryExecuted', function ($query) {
                Log::debug($query->sql . ' - ' . serialize($query->bindings));
            });
        }
    }
}

这会将查询记录到/storage/logs/laravel.log文件中