Laravel。使用

时间:2018-04-02 11:19:33

标签: php mysql database laravel controller

我有一个控制器,其中有一个字符串

$models = Model::with('table1', 'table2', 'table3', 'table4', 'table5')
->where('name', 'hello')->get();

问题是所有表中都包含字段name。如何指定所需?我试过这个:

->where('table3.name', 'hello')->get();

但是我收到错误 - 找不到字段

2 个答案:

答案 0 :(得分:0)

试试这个:

$models = Model::with('table1 AS t1', 'table2 AS t2', 'table3 AS t3', 'table4 AS t4', 'table5 AS t5')
->where('t1.name', 'hello')->get();

答案 1 :(得分:0)

with中创建的相对方法相关的

Model方法,它不是表名。您必须使用表名代替table_name_for_table3.name。但您可以使用whereHas方法

$search_string = "hello";
$models = Model::with('table1', 'table2', 'table3', 'table4', 'table5')
->whereHas('table3',function($t)use($search_string){
   $t->where('name',$search_string);
})
->where('name', 'hello')->get();

From Doc

  

这些方法允许您向a添加自定义约束   关系约束,例如检查评论的内容: