简体   繁体   中英

Laravel 4.x Alias a table using Eloquent while performing a join

I'm aware that in my Model I can alias my table like so:

protected $table = 'territories_sign_in_out AS tsio';

so that I can still use Eloquent to build collections but what about when I need to use the table in a join like this:

Territories::select('territories.id', 'tsio.signed_out')
           ->join('territories_sign_in_out', function($join) use ($id)
           {
               //
           })
           ->get();

Right now I get an error:

SQLSTATE[42000]: Syntax error or access violation: 1064 You have an error 
in your SQL syntax; check the manual that corresponds to your MySQL server 
version for the right syntax to use near 'as `tsio`.`publisher_id` = ? order 
by `territory_id` asc, `signed_in` asc' at line 1 (SQL: select * from 
`territories_sign_in_out` as `tsio` where `territories_sign_in_out` as 
`tsio`.`publisher_id` = 59 order by `territory_id` asc, `signed_in` asc)

Am I stuck just using Fluent?

DB::table('territories_sign_in_out AS tsio')...

I would like to also be able to build statements using Eloquent like this:

TerritoriesSignInOut::select('t.id', 't.label', 'tsio.signed_out', 'tsio.publisher_id')
                    ->join('territories AS t', 'tsio.territory_id', '=', 't.id')
                    ->whereNull('tsio.signed_in')
                    ->orderBy('t.label', 'ASC')
                    ->get();

and I can only do this by adding as tsio like I mentioned at the fore of this question.

To clarify table territories = model Territories . Table territories_sign_in_out = model TerritoriesSignInOut .

You need to alias it like:

Territories::select('territories.id', 'tsio.signed_out')
           ->join('territories_sign_in_out as tsio', function($join) use ($id) {
               //...
           })
           ->get();

To be more clear I'm re-writing the code again:

Territories::join('territories_sign_in_out as tsio', function($join) use ($id) {
               //...
           })
           ->select('territories.id', 'tsio.signed_out')
           ->get();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM