Laravel 获取与其属性同名的 Eloquent 关系
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/41460707/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Laravel get Eloquent relation by same name as its attribute
提问by kirgy
I have database tables like this:
我有这样的数据库表:
shoot: id, name, programme
programme: id, name
The eloquent relationship in the shoot is defined like this:
拍摄中的雄辩关系是这样定义的:
public function programme() {
return $this->belongsTo('App\Programme', 'programme', 'id');
}
When using dd()
, I can see this is working correctly:
使用时dd()
,我可以看到这是正常工作的:
dd(Shoot:where('id','=',1)->with('programme')->first());
// prints the object with programme listed under the relationship
However when I eager-load the shoot and attempt to get the programme object, I retrieve the shoot attribute "programme" instead. E.g.:
但是,当我急切加载拍摄并尝试获取程序对象时,我反而检索了拍摄属性“程序”。例如:
$shoot = Shoot:where('id','=',1)->with('programme')->first();
echo $shoot->programme; // returns 1, not App\Programme object.
Is there a solution to this without having to rewrite masses of the codebase?
有没有无需重写大量代码库的解决方案?
回答by Zakaria Acharki
You shouldn't use the same name for the both relationship
and column
name, else you'll receive always the column
name so try to edit one of them, I think the easiest one here is the relationship
name :
您不应该对两者relationship
和column
名称使用相同的名称,否则您将始终收到column
名称,因此请尝试编辑其中之一,我认为这里最简单的一个是relationship
名称:
public function programmeObj() {
return $this->belongsTo('App\Programme', 'programme', 'id');
}
Then call it as :
然后将其称为:
echo $shoot->programmeObj;
NOTE :But if you want to follow conventions you should replace the name attribute by programme_id
so :
注意:但是如果您想遵循约定,您应该将 name 属性替换为programme_id
:
public function programme() {
return $this->belongsTo('App\Programme', 'programme_id', 'id');
}
Hope this helps.
希望这可以帮助。
回答by user3402600
To achieve what you after you will need to do the following:
要实现您的目标,您需要执行以下操作:
$shoot = Shoot:where('id','=',1)->with('programme')->first();
$variable = $shoot->programme; // returns 1
$obj = $page->getRelationValue('programme') // returns App\Programme object.
回答by Robin Dirksen
This will returns always the column in your database if it exists, that's ID 1.
如果存在,这将始终返回数据库中的列,即 ID 1。
When you call dump($shoot);
you should get the array with all attributes. But when you run the following you should get the name:
当您调用时,dump($shoot);
您应该获得具有所有属性的数组。但是当您运行以下命令时,您应该得到名称:
Your model:
您的型号:
public function programmeData() {
return $this->belongsTo('App\Programme', 'programme', 'id');
}
And your controller:
还有你的控制器:
$shoot = Shoot:where('id','=',1)->first();
return $shoot->programmeData->name; // returns name
Hope this works!
希望这有效!