[英]How do I give same name to defination of two one-to-many relationships in Eloquent ORM
I am designing a toy project which is a twitter clone in Laravel-4 . 我正在设计一个玩具项目,它是Laravel-4中的一个Twitter克隆。 I have following relationships in model below : 我在以下模型中具有以下关系:
<?php
class Follower extends Eloquent {
protected $guarded = array();
public static $rules = array();
public function user_follower()
{
return $this->belongsTo('User','to_user_id');
}
public function user_following()
{
return $this->belongsTo('User','from_user_id');
}
}
A query for knowing following list of a user returns an Json object as below : 知道用户的以下列表的查询将返回一个Json对象,如下所示:
[
{
"id": 2,
"from_user_id": 1,
"to_user_id": 2,
"created_at": "2013-12-15 17:40:26",
"updated_at": "2013-12-15 17:40:26",
"user_follower": {
"id": 2,
"full_name": "Shyanne Champlin",
"username": "shyanne718",
"created_at": "2013-12-15 14:28:53"
}
},
{
"id": 4,
"from_user_id": 1,
"to_user_id": 4,
"created_at": "2013-12-15 17:40:26",
"updated_at": "2013-12-15 17:40:26",
"user_follower": {
"id": 4,
"full_name": "Vinnie Lang",
"username": "vinnie398",
"created_at": "2013-12-15 14:28:54"
}
}
]
For other query for knowing followers for a user, in result "user_follower" gets changed to "user_following". 对于其他了解用户关注者的查询,结果“ user_follower”更改为“ user_following”。 So my question is how do I define same function name for both relations so It returns user 'value' with same 'key' name for both 'following users' and 'followers'. 因此,我的问题是如何为两个关系定义相同的函数名称,以便为“跟随用户”和“跟随者”返回具有相同“键”名称的用户“值”。
I just tested your setup extensively, which seems to be working perfectly fine on my end. 我刚刚对您的设置进行了广泛的测试,看来我的工作效果很好。
I can think of 3 things: 我可以想到三件事:
Wrong definition of the with
method. with
方法的定义错误。 Should be: Follower::with(array('user_follower', 'user_following'))->get();
应该是: Follower::with(array('user_follower', 'user_following'))->get();
I never use underscores _
in my method naming. 我从未在方法命名中使用下划线_
。 I assume Laravel is expecting userFollower()
and userFollowing()
, while still returning underscores in the JSON result. 我假设Laravel期望userFollower()
和userFollowing()
,而仍然在JSON结果中返回下划线。
A bug in your distro of Laravel. 您的Laravel发行版中的错误。 Just run composer update
to be sure. 只需运行composer update
即可。 I just ran it and it still works, so at least the current distro works fine. 我只是运行它,它仍然有效,因此至少当前发行版可以正常工作。 (I use "laravel/framework": "4.1.*",
in composer.json) (我在composer.json中使用"laravel/framework": "4.1.*",
)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.