doucai9270 2018-03-27 09:09
浏览 46
已采纳

Laravel雄辩,模型中的条件(Constraining Eager Loads)不起作用

Here is My Controller's Code to get Order list with Condition apply in join table

$orders = Order::whereHas('order_carpets', function($q){
            $q->where('carpent_no', '1345');
        })->get();

Model Code looks something like this

class Order extends Model
{
    protected $table = 'orders';
    public function order_carpets()
    {
        return $this->belongsToMany(Order_carpet::class, 'orders', 'id', 'order_carpet_id');
    }

    public function customers()
    {
        return $this->belongsToMany(Customer::class, 'orders', 'id', 'customer_id');
    }
}

class Order_carpet extends Model
{
    public function orders()
    {
        return $this->hasMany(Order::class);
    }
}

The result I'm getting now is all data of table Order

  • 写回答

1条回答 默认 最新

  • dpa55065 2018-03-28 00:11
    关注

    The orders table appears in your main query and your subquery, without aliases.
    So where orders.id = orders.id refers to the same table twice and so is always true.

    The problem is the order_carpets relationship. It's actually a BelongsTo relationship:

    public function order_carpets()
    {
        return $this->belongsTo(Order_carpet::class, 'order_carpet_id');
    }
    

    The same goes for the customers relationship:

    public function customers()
    {
        return $this->belongsTo(Customer::class, 'customer_id');
    }
    

    You should probably rename them to order_carpet and customer.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 uniapp uview http 如何实现统一的请求异常信息提示?
  • ¥15 有了解d3和topogram.js库的吗?有偿请教
  • ¥100 任意维数的K均值聚类
  • ¥15 stamps做sbas-insar,时序沉降图怎么画
  • ¥15 买了个传感器,根据商家发的代码和步骤使用但是代码报错了不会改,有没有人可以看看
  • ¥15 关于#Java#的问题,如何解决?
  • ¥15 加热介质是液体,换热器壳侧导热系数和总的导热系数怎么算
  • ¥100 嵌入式系统基于PIC16F882和热敏电阻的数字温度计
  • ¥20 BAPI_PR_CHANGE how to add account assignment information for service line
  • ¥500 火焰左右视图、视差(基于双目相机)