laravel Eloquent - 使用字符串值而不是列标题连接子句

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/24449223/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-14 09:43:00  来源:igfitidea点击:

Eloquent - join clause with string value rather than column heading

phpmysqllaraveleloquent

提问by benJ

I have a question regarding join clauses in Eloquent, and whether you can join on a string value rather than a table column.

我有一个关于 Eloquent 中连接子句的问题,以及是否可以连接字符串值而不是表列。

I have the code below querying a nested set joining parent/child records in a table 'destinations' via a table 'taxonomy'.

我有下面的代码通过表“分类法”查询连接表“目的地”中的父/子记录的嵌套集。

The second $joinstatement in the closure is the one causing an issue; Eloquent assumes this is a column, when I would actually just like to join on t1.parent_type = 'Destination'- ie, t1.parent_typeshould = a string value, Destination.

$join闭包中的第二个语句是导致问题的语句;Eloquent 假设这是一个列,而我实际上只是想加入t1.parent_type = 'Destination'- 即,t1.parent_typeshould = 一个字符串值,Destination.

$result = DB::connection()
    ->table('destinations AS d1')
    ->select(array('d1.title AS level1', 'd2.title AS level2'))
    ->leftJoin('taxonomy AS t1', function($join) {
        $join->on('t1.parent_id', '=', 'd1.id');
        $join->on('t1.parent_type', '=', 'Destination');
    })
    ->leftJoin('destinations AS d2', 'd2.id', '=', 't1.child_id')
    ->where('d1.slug', '=', $slug)
    ->get();

Is it possible to force Eloquent to do this? I've tried replacing 'Destination'with DB::raw('Destination')but this does not work either.

是否可以强制 Eloquent 这样做?我试过替换为'Destination'DB::raw('Destination')但这也不起作用。

Thanking you kindly.

谢谢你。

回答by mukund

Another best way to achieve same is :

实现相同目标的另一种最佳方法是:

$result = DB::connection()
    ->table('destinations AS d1')
    ->select(array('d1.title AS level1', 'd2.title AS level2'))
    ->leftJoin('taxonomy AS t1', function($join) {
        $join->on('t1.parent_id', '=', 'd1.id');
        $join->where('t1.parent_type', '=', 'Destination');
    })
    ->leftJoin('destinations AS d2', 'd2.id', '=', 't1.child_id')
    ->where('d1.slug', '=', $slug)
    ->get();

Replace your onwith where

替换你onwhere

回答by Krishna Raj K

try using DB::raw("'Destination'")

尝试使用 DB::raw("'Destination'")