mysql - Eloquent whereIn 不与关系一起工作

标签 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}

最佳答案

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

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

相关文章:

PHP:带有 MySQL 的多语言系统

mysql - 如何将此 Excel 公式转换为 SQL?

laravel - 将 ffmpeg 命令输出存储到 aws s3

php - 拉维尔 4 : Eloquent relationship get all data

php - 防止 Eloquent 查询中的模型水合作用

php - MySQL:多个经纬度的附近位置

MYSQL 3 按年份记录连续出现次数

php - Laravel 5.2 有条件更新数据库

laravel - 隐藏Laravel MethodNotAllowedHttpException

php - PDO 中字符串附加问号