我需要在我的Model中定义复合外键。目前不支持它。所以,我尝试在我的模型中运行本机查询。
我有两个表(vwAlarm, vwYfUserToSiteMappings
)两个表都有两列。
CompanyId,SITECODE
我希望通过连接两个表中的两列来返回单行。
这是我的模特;
class Alarm extends Model
{
protected $table = 'vwAlarm';
protected $primaryKey = 'AlarmId';
..
public function Site()
{
$rec = \DB::table('vwAlarm')
->join('vwYfUserToSiteMappings', 'vwAlarm.SiteCode', '=', 'vwYfUserToSiteMappings.SiteCode')
->join('vwYfUserToSiteMappings','vwAlarm.CompanyId', '=', 'vwYfUserToSiteMappings.CompanyId')
->first();
return $rec;
}
我得到了
QueryException
SQLSTATE[42000]: [Microsoft][ODBC Driver 13 for SQL Server][SQL Server]The objects "vwYfUserToSiteMappings" and "vwYfUserToSiteMappings" in the FROM clause have the same exposed names. Use correlation names to distinguish them. (SQL: select top 1 * from [vwAlarm] inner join [vwYfUserToSiteMappings] on [vwAlarm].[SiteCode] = [vwYfUserToSiteMappings].[SiteCode] inner join [vwYfUserToSiteMappings] on [vwAlarm].[CompanyId] = [vwYfUserToSiteMappings].[CompanyId])
如何更正我的查询?
答案 0 :(得分:1)
你应该试试这个:
$rec = \DB::table('vwAlarm')
->join('vwYfUserToSiteMappings AS vwSiteCode', 'vwSiteCode.SiteCode', '=', 'vwAlarm.SiteCode')
->join('vwYfUserToSiteMappings AS vwCompanyId','vwCompanyId.CompanyId', '=', 'vwAlarm.CompanyId')
->first();
希望这对你有用!!!
答案 1 :(得分:0)
为表名设置别名,如下所示
$rec = \DB::table('vwAlarm')
->join('vwYfUserToSiteMappings AS vw1', 'vwAlarm.SiteCode', '=', 'vw1.SiteCode')
->join('vwYfUserToSiteMappings AS vw2','vwAlarm.CompanyId', '=', 'vw2.CompanyId')
->first();