Eloquent - 使用字符串值而不是列标题的join子句

ben*_*enJ 10 php mysql laravel eloquent

我有一个关于Eloquent中的join子句的问题,以及你是否可以加入字符串值而不是表列.

我有下面的代码查询嵌套集合,通过表'分类法'加入表'目的地'中的父/子记录.

$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();
Run Code Online (Sandbox Code Playgroud)

是否有可能强迫Eloquent这样做?我尝试过更换'Destination',DB::raw('Destination')但这也不起作用.

亲切地感谢你.

muk*_*und 20

实现同样目标的另一个最佳方法是:

$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();
Run Code Online (Sandbox Code Playgroud)

更换你onwhere


Kri*_*j K 7

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

  • @Synchro嗯..我没看到。我还没有检查评论。他本可以回答自己的问题,而不是发表评论。 (2认同)