【问题标题】:how to use where for relationship in laravel eloquent?如何在 laravel eloquent 中使用 where 进行关系?
【发布时间】:2016-09-13 15:11:59
【问题描述】:

我想在另一个关系上使用 where 子句,而不是我当前的选择模型,如下表

table Customer
-------id-----customer_name

Table ModelA


table Customer
-------id-----fk_custome_id

table ModelB
-------id-----fk_ModelA_id

控制器中的功能

$data['data'] = customer::with(['modelA','modelA.modelB'])
 ->where('fk_customer_id', 2)->get();

客户模型

final function ModalA (){
    return $this->hasMany('App\Models\ModelA', 'fk_customer_id', 'id');
}

ModelA 模型

final function Modelb (){
    return $this->hasMany('App\Models\ModelB', 'fk_modelA_id', 'id');
}

错误: 我会得到如下错误,因为 select sql 在表 customer 中找不到列名 fk_customer_id,那么我如何在哪里使用 fk_customer_id(在表 ModelA 中)。

【问题讨论】:

    标签: php laravel-5 eloquent


    【解决方案1】:

    你可以用whereHaslike:

    $data['data'] = customer::with(['modelA','modelA.modelB'])
         ->whereHas('modelA', function ($query) {
             $query->where('fk_customer_id', 2);
         })->get();
    

    这是因为当您使用时只是急切加载约束,但您不会将其附加到主查询(customer 模型)。所以有两种方法:一种是现代的,使用whereHas 或使用join 查询。

    【讨论】:

      猜你喜欢
      • 2015-07-05
      • 2016-12-01
      • 2015-10-02
      • 1970-01-01
      • 2013-09-09
      • 1970-01-01
      • 2013-09-28
      • 2015-03-27
      • 1970-01-01
      相关资源
      最近更新 更多