Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Eloquent - join clause with string value rather than column heading

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

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

The second $join statement 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_type should = a string value, 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.

Thanking you kindly.

like image 648
benJ Avatar asked Jun 27 '14 10:06

benJ


2 Answers

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 on with where

like image 82
mukund Avatar answered Nov 18 '22 22:11

mukund


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

like image 9
Krishna Raj Avatar answered Nov 18 '22 22:11

Krishna Raj