【问题标题】:How do I search by a table included using with() statement如何通过使用 with() 语句包含的表进行搜索
【发布时间】:2021-06-08 17:56:51
【问题描述】:

我正在尝试使用 with 搜索已连接表上的列。 According to laravel 以下应该可以工作。

$lineItems = Invoice::with(['invoiceHeader' => function ($query) {
    $query->where('community_id', '=', 1);
    }, 'invoiceLineItems'])
        ->limit(10)
        ->get()
        ->toArray();

但是,我没有从invoiceHeader 表中得到任何信息,而且我得到了所有可用的发票。如果我取出函数,我会得到相同的结果,但会显示 invoiceHeader 的表值。

$lineItems = Invoice::with(['invoiceHeader', 'invoiceLineItems'])
        ->limit(10)
        ->get()
        ->toArray();

看来我可能正在做一些right join 的事情,我在其中获得了所有发票,但在适用于外键时只有 invoiceHeader 值。

编辑:

我将->toSql(); 放在limit() 之后,它表明我只得到以下内容。

"select * from `invoice` limit 10"

【问题讨论】:

  • 你能发布关系和数据库模式吗?你在发票头表中是否有 community_id=1 的记录

标签: laravel eloquent laravel-8


【解决方案1】:

您应该使用whereHaswith 混合使用:

$lineItems = Invoice::with(['invoiceHeader', 'invoiceLineItems'])
    ->whereHas('invoiceHeader', function ($query) {
        return $query->where('community_id', 1);
    })
    ->limit(10)
    ->get()
    ->toArray();

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2017-06-08
    • 2019-12-25
    • 1970-01-01
    • 1970-01-01
    • 2017-08-22
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多