【问题标题】:Laravel. Use the table name in the where拉拉维尔。在 where 中使用表名
【发布时间】:2018-09-11 14:40:31
【问题描述】:

我有一个控制器,里面有一个字符串

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

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

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

但我收到一个错误 - 找不到字段

【问题讨论】:

  • table3 是关系而不是表名吗?

标签: php mysql database laravel controller


【解决方案1】:

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

这些方法允许您将自定义约束添加到 关系约束,比如查看评论内容:

【讨论】:

    【解决方案2】:

    试试这个:

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

    【讨论】:

    • 调用模型 [App\\ n_Models] 上的未定义关系 [table1 AS sm]
    • 别名可以通过whereHas方法制作为whereHas(tablea as t1,function({$t}))
    猜你喜欢
    • 2018-10-18
    • 1970-01-01
    • 1970-01-01
    • 2018-08-19
    • 2018-07-27
    • 2018-05-10
    • 1970-01-01
    • 2020-03-29
    • 1970-01-01
    相关资源
    最近更新 更多