我正在尝试以下查询以获取特定类别的所有问题。
$categories = Category::with('question')->whereIn('id', [2,3])->get();
我的关系定义如下
class Category extends Model {
public function questions()
{
return $this->hasMany('App\Question');
}
}
和
class Question extends Model {
public function category()
{
return $this->belongsTo('App\Category');
}
}
结果为空的问题
{id: 2, name: "Communicatie", question: null}
最佳答案
首先,不要让你的生活变得艰难。您正在尝试获取问题
,但您正在调用
$categories = ...
真的,如果你要问题,那就从问题开始,这样会更容易找到解决方案:
$questions = Question:: .... ->get();
现在,只需找到阅读 the docs我们开始吧:
$questions = Question::whereHas('catgory', function ($q) use ($catsIds) {
$q->whereIn('categories.id', $catsIds);
})->get();
顺便说一句,您的方式也是获得您所要求的,只是获得它很麻烦:
$categories = Category::with('question')->whereIn('id', [2,3])->get();
foreach ($categories as $category)
{
$category->questions; // collection of questions you wanted
}
// you could now merge the questions of all the categories, but it's not the way
关于mysql - Eloquent whereIn 不与关系一起工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29029610/