douyiyang6317 2014-08-25 20:29
浏览 171
已采纳

Laravel 4.x在执行连接时使用Eloquent对表进行别名

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.

  • 写回答

1条回答 默认 最新

  • dpquu9206 2014-08-25 20:32
    关注

    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();
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
编辑
预览

报告相同问题?

手机看
程序员都在用的中文IT技术交流社区

程序员都在用的中文IT技术交流社区

专业的中文 IT 技术社区,与千万技术人共成长

专业的中文 IT 技术社区,与千万技术人共成长

关注【CSDN】视频号,行业资讯、技术分享精彩不断,直播好礼送不停!

关注【CSDN】视频号,行业资讯、技术分享精彩不断,直播好礼送不停!

客服 返回
顶部