如果两个表之间有关系,我使用with
函数从另一个表中获取考虑条件值的记录。例如:
Table::where('column1', 'text1')->with('table2.column2', 'text2')
我的问题是,如何使用whereIn
函数在table2
中设置允许值的数组?
Table::where('column1', 'text1')->whereIn('table2.column2', ['text2', 'text3'])
我会和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
方法。
试试这个
Table::where('column1', 'text1')
->whereHas('table2',function($q) {
$q->whereIn('column2', ['text2','text3']);
});
您必须在模型中定义关系
这是最佳做法