【问题标题】:Eloquent: filter both pivot table and model tableEloquent:过滤数据透视表和模型表
【发布时间】:2017-09-30 14:35:51
【问题描述】:

雄辩的关系如下:

“stores”属于许多“storedaytimes”(属于许多)

数据透视表 (store_day_time_stores) 有一个名为“user_id”的键,storedaytimes 表有一个名为“日期”的字段。

我想根据给定的“user_id(来自数据透视表)”和“开始”和“结束”日期(来自 storedaytime 表)过滤“storedaytimes”中的记录。

我当前的查询是

$storedaytime->stores()
    ->wherePivot('user_id','=',$user)
    ->orderBy('date')
    ->where('date','>=',$start)
    ->where('date','<=',$end)->get();

它产生了一个看起来非常可怕但不起作用的查询:

SQLSTATE[42S22]:未找到列:1054 中的未知列“日期” 'where 子句' (SQL: select stores.*, order_day_time_store.order_day_time_idpivot_order_day_time_id, order_day_time_store.store_idpivot_store_id, order_day_time_store.user_id 作为pivot_user_id, order_day_time_store.id as pivot_id from stores 内部连接 order_day_time_store stores.id = order_day_time_store.store_id 在哪里 order_day_time_store.order_day_time_id 为空且 order_day_time_store.user_id = 4 和 date >= 2017-05-01 12:00:00 和date date asc 订购)

请帮忙。谢谢:3

【问题讨论】:

    标签: mysql laravel eloquent


    【解决方案1】:

    尝试以下方法:

    $storedaytime->stores()
        ->wherePivot('user_id','=',$user)
        ->whereBetween('storedaytimes.date', [$start, $end])
        ->orderBy('storedaytimes.date')
        ->get();
    

    建议 order by 子句放在 SQL 语句的末尾,除非您必须事先对日期进行排序。在你的情况下没有理由这样做,所以把它放在最后。

    【讨论】:

    • 注明重新订购。这不起作用,它给出了这个错误: SQLSTATE[42S22]: Column not found: 1054 Unknown column 'order_day_time_store.order_day_time_store.user_id' in 'where clause' (SQL: select stores.*, order_day_time_store.order_day_time_idpivot_order_day_time_idorder_day_time_storestore_idpivot_store_idorder_day_time_storeuser_idpivot_user_idorder_day_time_storeidpivot_idstores内部联接order_day_time_store on stores.id = order_day_time_store.store_id 其中order_day_time_store.order_day_time_id 为空且
    • 好的,然后从 wherePivot 子句中删除“store_day_time_stores”
    【解决方案2】:

    自己想通​​了:以下查询有效:

    $storedaytime ->where('date','>=',$start)
    ->where('date','<=',$end)
    ->whereHas('stores',function($q) use($user){
                    $q->where('user_id',$user);})
    ->get();
    

    【讨论】:

      猜你喜欢
      • 2013-09-03
      • 2017-10-17
      • 1970-01-01
      • 2014-01-12
      • 2019-01-25
      • 1970-01-01
      • 1970-01-01
      • 2021-01-09
      • 1970-01-01
      相关资源
      最近更新 更多