【问题标题】:Laravel Eloquent hasOneThrough RelationLaravel Eloquent hasOneThrough 关系
【发布时间】:2020-06-02 15:21:15
【问题描述】:

我在 Laravel 上学习雄辩的关系,我在 hasonethrough 上遇到了问题 通过使用与 Laravel 文档相同的表格设计

tables
mechanics (id, name)
cars (id, model, mechanic_id)               
owners (id, name, car_id)

然后我在 mechanic model 上定义关系来访问车主

class Mechanic extends Model
{
    public function carOwner() {
        return $this->hasOneThrough('App\Owner', 'App\Car');
    }   
}    

这将返回

array:4 [▼
  "id" => 1
  "name" => "Ricky"
  "car_id" => 1
  "laravel_through_key" => 1
]

我的问题是我可以使用我的hasOnethrough 关系获取汽车模型吗?

【问题讨论】:

    标签: laravel eloquent relation


    【解决方案1】:

    是的,你可以....

    在您的 Owner 模型中设置汽车关系

    class Owner extends Model
    {
        public function car() {
            return $this->belongsTo('App\Car','car_id');
        }   
    }   
    

    那么你可以像这样使用这些关系:

    $value=Mechanic::find($mechanic_id)->with('carOwner.car')->get();
    

    $value 将持有车主和他的车

    【讨论】:

      猜你喜欢
      • 2020-10-24
      • 2023-02-04
      • 1970-01-01
      • 1970-01-01
      • 2020-10-23
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多