Eloquent whereIn 不处理关系

Eloquent whereIn not working with relation

我正在尝试以下查询获取特定类别的所有问题

$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}

你的 question 模型不应该是 hasMany 关系而不是 belongsTo 吗?您基本上在两个方向上都使用了 belongsTo,这绝对是不正确的。是多对多关系还是什么?

编辑:我的意思是你的 Question 模型应该是 belongsToCategory 应该是 hasMany :)

class Category extends Model {

    public function questions()
    {
        return $this->hasMany('App\Question');
    }
}


class Question extends Model {

    public function category()
    {
        return $this->belongsTo('App\Category');
    }
}

首先,不要让你的生活变得艰难。您正在尝试获取 questions 但您正在调用

$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