【问题标题】:how to write where condition in relation table in Laravel in query如何在查询中在 Laravel 的关系表中写入 where 条件
【发布时间】:2021-03-24 12:37:52
【问题描述】:

我有 3 个表,即 Resort、Booking、Expense,这些表是通过关系连接的。代码如下,

$resorts = Resort::where('status',1)->with('bookings')->withSum('bookings', 'amount')
        ->with('expenses')->withSum('expenses', 'amount')->get();

我想使用date 字段对该表进行排序。如何在此查询中使用 wherebetween 进行预订和费用?

【问题讨论】:

    标签: laravel relation


    【解决方案1】:

    你可以像这样在with() 中传递数组

    $resorts = Resort::where('status', 1)
        ->with(
            ['bookings' => function ($q) {
                $q->wherebetween('colName', ['startDate','endDate']);
            }]
        )->withSum('bookings', 'amount')
        ->with(
            ['expenses' => function ($q) {
                $q->wherebetween('colName', ['startDate','endDate']);
            }]
        )->withSum('expenses', 'amount')
        ->get();
    

    参考链接https://laravel.com/docs/8.x/eloquent-relationships#constraining-eager-loads

    【讨论】:

    • 使用这个代码我得到了错误Too few arguments to function App\Http\Controllers\IncomeExpenseController::App\Http\Controllers\{closure}()
    • IncomeExpenseController ?把这段代码也放进去,然后我就可以知道这是什么错误
    猜你喜欢
    • 2021-12-02
    • 1970-01-01
    • 2021-12-06
    • 2021-08-30
    • 1970-01-01
    • 2019-07-01
    • 1970-01-01
    • 2021-08-24
    • 2015-06-25
    相关资源
    最近更新 更多