dsfhe34889
2018-01-03 07:28
浏览 67
已采纳

Laravel Eloquent与同桌的多重关系

I have the following table:

Table: rental_request
Columns:
id int(11) AI PK 
user_id int(11) 
address text 
number varchar(45) 
kvm varchar(45) 
rental varchar(45) 
zip varchar(45) 
city varchar(45) 
timestamp datetime 
created_at datetime 
updated_at datetime 
caseworker int(11)

Where user_id and caseworker points to my users table.

Now i am attempting to create this relationship in my Laravel application:

    class rental_request extends Model
{
    protected $table = 'rental_request';
    protected $fillable = ['user_id','address', 'number', 'kvm','rental','zip','city', 'caseworker'];

    public function user()
    {
        return $this->belongsTo('App\User', 'user_id');
    }

    public function caseworker()
    {
        return $this->hasOne('App\User', 'user_id', 'caseworker');
    }
}

In my controller I collect the data from the table using:

rental_request::orderBy('id', 'desc')->get();

Now, this actually works but only for the user and not for the caseworker.

Which means I have a user object on my result but not a caseworker object.

Can anyone tell me what I've done wrong?

图片转代码服务由CSDN问答提供 功能建议

我有下表:

 表:rental_request \  nColumns:
id int(11)AI PK 
user_id int(11)
address text 
number varchar(45)
kvm varchar(45)
rental varchar(45)
zip varchar(45)
city varchar(45)\  ntimestamp datetime 
created_at datetime 
updated_at datetime 
caseworker int(11)
   
 
 

其中 user_id caseworker 指向 到我的 users 表。

现在我试图在 Laravel 应用程序中创建这种关系: \ n

 类rental_request扩展Model 
 {
 protected $ table ='rental_request'; 
 protected $ fillable = ['user_id','address','number','kvm','rental'  ,'zip','city','caseworker']; 
 
公共函数user()
 {
返回$ this-> belongsTo('App \ User','user_id'); 
}  
 
公共函数caseworker()
 {
返回$ this-> hasOne('App \ User','user_id','caseworker'); 
  } 
} 
   
 
 

在我的控制器中,我使用以下方法从表中收集数据:

  rental_request ::  orderBy('id','desc') - > get(); 
   
 
 

现在,这实际上有效但仅适用于用户而不是 caseworker

这意味着我的结果上有 user 对象,但 caseworker < / code> object。

谁能告诉我我做错了什么?

  • 写回答
  • 好问题 提建议
  • 追加酬金
  • 关注问题
  • 邀请回答

2条回答 默认 最新

相关推荐 更多相似问题