雄辩在哪里不与关系一起工作

时间:2015-03-13 10:13:02

标签: mysql laravel eloquent

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

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

2 个答案:

答案 0 :(得分:2)

首先,不要让你的生活变得艰难。您正试图获取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

答案 1 :(得分:1)

您的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');
    }
}
相关问题