Laravel 三个模型之间的关系

Laravel Relationship between Three Models

sold_items:
id    order_id   customer_id   name      
--    --------   -----------   ----
1     5          14            An object

orders:
id      po_num
--      ------
...     ...
5       123


customers:
id      name
--      ----
...     ...
14      John Doe

一个SoldItem有一个order_id和一个customer_id

我试图通过 SoldItem 定义 Order 与其 Customer 之间的 hasOne 关系必须在 Order 模型的 table.

中插入 customer_id

hasOneThrough 似乎是解决方案,但我不知道从那里去哪里,或者甚至是答案?

<?php

namespace App;

use Illuminate\Database\Eloquent\Model;

class Order extends Model
{
    public $timestamps = false;
    protected $guarded = ['id'];

    public function sold_items()
    {
        return $this->hasMany('App\SoldItem');
    }

    public function customer()
    {
        // return $this->hasOneThrough();
    }
}

我最终通过它的 sold_items 使 Customer 成为 Orderattribute

<?php

namespace App;

use Illuminate\Database\Eloquent\Model;

class Order extends Model
{
    public $timestamps = false;
    protected $guarded = ['id'];

    public function sold_items()
    {
        return $this->hasMany('App\SoldItem');
    }

    public function getCustomerAttribute()
    {
        return $this->sold_items->first()->customer;
    }
}

客户模型

{

    public function sold_items()
    {
        return $this->hasMany('App\SoldItem');
    }


}

订单型号

{

    public function sold_items()
    {
        return $this->hasOne('App\SoldItem');
    }


}

对于 SoldItem 模型

{

    public function customer()
    {
        return $this->belongsto('App\Cutomer');
    }

     public function order()
    {
        return $this->belongsto('App\Order');
    }

}

我更喜欢先处理他们的关系,然后使用 with() 函数来获取他们的值。

use App\Customer;

$customer = Customer::with('sold_items','sold_items.order')->get();