我只是想使用BelongsTo
关系来检索记录, 这是方案:
roles:
- id
- title
users:
- id
- Role_ID
我正在使用SQL Server
作为数据库,因此Role_ID
可以指向我认为:Drole_id
。
这是模型中属于关系的代码User
:
public function role()
{
return $this->belongsTo('AppRole');
}
我也尝试过这样的:
public function role()
{
return $this->belongsTo('AppRole', 'id', 'Role_ID');
}
但是无论参数是什么,它都不起作用,当我得到查询日志时,它看起来像:
bindings: []
query: "select * from [roles] where 0 = 1"
time: 1.49
以下是我尝试访问Controller
关系的方法:
User::with(['role'])->get($someColumns)
我只是多次与这个问题作斗争,但不知道问题出在哪里。
任何帮助,不胜感激。
谢谢大家。
你必须在get((列中包含外键
User::with(['role'])->get(Role_ID, OthersColumns)
在模型中尝试这种关系。
public function role()
{
return $this->belongsTo('AppRole', 'Role_ID','id');
}
谢谢大家,@Dilip提示帮助我解决了这个问题。
请参阅我更新的问题这一行:
User::with(['role'])->get($someColumns)
实际上问题出在$someColumns上,因为当我在get中提到某些列的名称时,它导致了问题,但是当我将其替换为以下内容时:
User::with(['role'])->get()
成功了
所以简单的解决方案是在获取关系belongsTo
时不提及列名