php - Laravel 5.1内部联接查询中的问题

原文 标签 php sql laravel-5 eloquent laravel-5.1

Issue in Laravel 5.1 Inner Join Query

Below is my Query in Laravel 5.1

\App\Models\Project\Bids\ProjectBid_Model
::selectRaw('B.*')
->join('tblproject P','B.projectid','=','P.projectid')
->where('P.WhoCreatedTheProject',14)
->first()

and below is the equivalant query

select B.* from `tblprojectbid` 
inner join `tblproject P` on `B`.`projectid` = `P`.`projectid` 
where `P`.`WhoCreatedTheProject` = 14 limit 1

What's the problem ?

Please check the line 1 in Query: select B.* from tblprojectbid.

What's the question ?

How can I change

select B.* from tblprojectbid

to

select B.* from tblprojectbid B

Answer

If you want to use Eloquent I'm afraid there is no easy way to do it.

I use in this case full table name for model for instance

\App\Models\Project\Bids\ProjectBid_Model
::selectRaw('bid_table.*')
->join('tblproject AS P','bid_table.projectid','=','P.projectid')
->where('P.WhoCreatedTheProject',14)
->first()

However it's also possible that you set alias in ProjectBid_Model:

protected $table = 'bid_table AS B';

The con is you will have this table always aliased with B, so in case you have 2 models with same alias (in this case B), you won't be able to change it later just for one table, so I think the better is 1st approach (without using alias)

翻译

以下是我在Laravel 5.1中的查询

\App\Models\Project\Bids\ProjectBid_Model
::selectRaw('B.*')
->join('tblproject P','B.projectid','=','P.projectid')
->where('P.WhoCreatedTheProject',14)
->first()


下面是等价查询

select B.* from `tblprojectbid` 
inner join `tblproject P` on `B`.`projectid` = `P`.`projectid` 
where `P`.`WhoCreatedTheProject` = 14 limit 1


有什么问题 ?

请检查查询:select B.* from tblprojectbid中的第1行。

问题是什么 ?

我该如何改变

select B.* from tblprojectbid



select B.* from tblprojectbid B
最佳答案
如果您想使用Eloquent,恐怕没有简单的方法可以做到。

我在这种情况下例如使用模型的完整表名

\App\Models\Project\Bids\ProjectBid_Model
::selectRaw('bid_table.*')
->join('tblproject AS P','bid_table.projectid','=','P.projectid')
->where('P.WhoCreatedTheProject',14)
->first()


但是,也有可能在ProjectBid_Model中设置别名:

protected $table = 'bid_table AS B';


缺点是您将使该表始终使用B作为别名,因此如果您有2个具有相同别名的模型(在本例中为B),则以后将无法仅对一个表进行更改,因此我认为更好的是第一种方法(不使用别名)
相关推荐

php - 控制PHP ldap分页-结果数和页码

php - 带有PHPStorm 10的PHP7

php - 如何防止第二个正则表达式重新替换?

php - 如何在PHP的$ _SESSION中保存值并进行检索

php - 与特质的定义顺序和内容有关的“未找到特质错误”

php - 按费用和名称对数组进行排序

php - WAMP上的Mysqli,错误-连接尝试失败

php - laravel查询返回奇怪的顺序

php - Silverstripe 3.2-如何在不同选项卡的ModelAdmin中管理同一数据对象的不同列表

php - 在SQL或脚本中排除ID