简体   繁体   English

Laravel通过与其属性相同的名称获得Eloquent关系

[英]Laravel get Eloquent relation by same name as its attribute

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. 然而,当我急切地加载拍摄并尝试获取程序对象时,我会检索拍摄属性“程序”。 Eg: 例如:

$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? 是否有解决方案,而无需重写大量的代码库?

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 : 你不应该为relationshipcolumn名使用相同的名称,否则你将始终收到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 : 注意:但是如果你想遵循约定,你应该用programme_id替换name属性,这样:

public function programme() {
    return $this->belongsTo('App\Programme', 'programme_id', 'id');
}

Hope this helps. 希望这可以帮助。

This will returns always the column in your database if it exists, that's ID 1. 这将始终返回数据库中的列(如果存在),即ID 1。

When you call dump($shoot); 当你调用dump($shoot); you should get the array with all attributes. 你应该获得具有所有属性的数组。 But when you run the following you should get the name: 但是当你运行以下内容时,你应该得到这个名字:

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! 希望这个有效!

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.

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM