mysql - 从 table1 检索数据但在 table2 中进行比较 - Laravel Eloquent

标签 mysql laravel laravel-5 laravel-5.5 laravel-query-builder

我有如下查询:

Relation1::with('relation2') 
->select('relation_1_columns')       
->where('relation_2_column', $relation2->id)  //Throws unknown column error
->where('relation_2_column', 1)               //Throws unknown column error
->get()->toArray();

如果我这样做:

Relation1::with('relation2') 
->select('relation_1_columns')       
->where('relation2.relation_2_column1', $relation2->id)  //Throws unknown column `relation2.relation_2_column` error
->where('relation2.relation_2_column2', 1)               //Throws unknown column `relation2.relation_2_column` error
->get()->toArray();

如何使用 where 子句 对使用 with 附加的表进行检查

最佳答案

使用whereHas() :

Relation1::with('relation2')
      ->select('relation_1_columns')
      ->whereHas('relation2', function($q) use ($relation2){
            $q->where('relation_2_column1', $relation2->id)->where('relation_2_column2', 1);
       })             
      ->toArray();

关于mysql - 从 table1 检索数据但在 table2 中进行比较 - Laravel Eloquent ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48851361/

相关文章:

php - 不唯一的表/别名 : 'products'

php - Laravel 5.2 Builder插入替换多行

laravel - Laravel 如何解码 HTTP 请求正文 Content-Type : application/x-www-form-urlencoded when using api call

php - 使用 Laravel 任务调度请求 URL

php - ReflectionException 在 Composer 更新存在的文件时抛出

mysql 移动结果集底部的行

mysql - Ajax/JQuery id 引用多个表行

mysql - 如何在 SQL 中创建多语言 Unicode 文本属性?

Laravel 如何下载目录中的所有文件

laravel - 关闭 Laravel artisan 命令的 ANSI 颜色