如何在另一个表上使用Laravel Eloquent whereIn函数?

问题描述 投票:0回答:2

如果两个表之间有关系,我使用with函数从另一个表中获取考虑条件值的记录。例如:

Table::where('column1', 'text1')->with('table2.column2', 'text2')

我的问题是,如何使用whereIn函数在table2中设置允许值的数组?

Table::where('column1', 'text1')->whereIn('table2.column2', ['text2', 'text3'])

laravel eloquent
2个回答
1
投票

我会和Laravel's Constrained eager load一起去加载你们的关系。

Table::where('column1', 'text1')
    ->with(['table2' => function ($query) {
        $query->whereIn('column2', ['text2', 'text3'])
    }])
    ->get();

如果您不需要加载关系,那么使用@bhavinjr提供的whereHas解决方案是最好的。


从文档:

渴望加载多个关系

有时您可能需要在单个操作中急切地加载几个不同的关系。为此,只需将其他参数传递给with方法:

$books = App\Book::with(['author', 'publisher'])->get();

限制急切负荷

有时您可能希望加载关系,但也为热切加载查询指定其他查询条件。这是一个例子:

$users = App\User::with(['posts' => function ($query) {
    $query->where('title', 'like', '%first%');
}])->get();`

您可以查看Laravel API以更深入地了解with方法。


1
投票

试试这个

Table::where('column1', 'text1')
    ->whereHas('table2',function($q) {
        $q->whereIn('column2', ['text2','text3']);
    });

您必须在模型中定义关系

这是最佳做法

参考:Laravel Eloquent Relationship

参考:Query On Relationship

© www.soinside.com 2019 - 2024. All rights reserved.