2013-05-11 147 views
0

OK,这里是我的代码:从我的模型,我的人际关系Laravel预先加载

// message model 
    public function profile() { 
     return $this->has_one('Profile', 'id'); 
    } 

// profile model 
    public function message(){ 
     return $this->has_many('message', 'id')->order_by('created_at', 'asc'); 
    } 

我的控制器:

public function get_MyMessages(){ 
     $per_page = 50; // results per page 
     $messages = Message::with('profile')->where('receiver_id', '=', Auth::user()->id)->or_where('sender_id', '=', Auth::user()->id)->take($per_page); 

     $messages = $messages->paginate($per_page); 
     $messages->appends(array($per_page))->links(); 


     $data = array(// data to pass to view 
     'title' => 'My Messages', 
     'messages' => $messages, 
    ); 
    return View::make('myProfile.myMessages',$data); // create view 
} 

在我看来,我可以这样做:

@foreach($messages->results as $message) 
    {{ $message->message }} 
@endforeach 

其中一期工程好,但是当我尝试:{{$ messages-> profile-> first_name}}

我得到以下错误:尝试获取非对象的属性 如果我尝试:{{print_r($ message-> profile}}所有数据都在那里,我只是无法访问它。

我已经尝试了一切,我做错了什么?

回答

1
// message model 
    public function profile() { 
     //the following statement means that every message has a profile (not true): 
     //instead, let's define the other side of the profile relationship. 
     return $this->has_one('Profile', 'id'); 
    } 

// profile model 
    public function message(){ 
     //the following statement means that a profile has many messages (true) 
     return $this->has_many('message', 'id')->order_by('created_at', 'asc'); 
    } 

此代码基本上意味着:

The profile has many messages, and each message has a profile.

在这些关系声明,您创建仅合作关系的一部分,但不是接收端。根据你的代码,我假设你使用的是Laravel 3(Laravel 4的关系是骆驼式的,而不是蛇式的)。

以下是基于Laravel 3的校正:

// message model 
    public function profile() { 
     return $this->belongs_to('Profile', 'id'); 
    } 

// profile model 
    public function message(){ 
     return $this->has_many('message', 'id')->order_by('created_at', 'asc'); 
    } 

该代码表示​​:

The profile has many messages, and the messages belong to the profile.

编辑: 刀片语法也需要被编辑。 使用{{ $messages->profile->first_name }}调用$messages变量的方法profile,该变量返回延迟加载查询的结果,但不返回消息对象(或模型实例)。请记住,型号message.phpprofile.php代表一个对象(所以一个消息或一个配置文件)。包含在$messages中的查询是一个非对象,它既不是简档也不是消息,而是消息的集合(或组)。

foreach循环的工作原理是因为它基本上破坏了$messages内部要使用的对象列表,在foreach标签内部,您指定了要对每个对象执行的操作,在您的情况下,您想要显示每个对象。在这个foreach循环中,您可以成功访问profile方法。

也就是说,你可以这样做:

@foreach($messages->results as $message) 
    {{ $message->message }} 
    {{ $message->profile->first_name }} 
@endforeach 

如果你不希望每个消息中显示的轮廓:

获取通过身份验证用户的个人资料,以显示他们的个人资料,你可以做Auth::user()->profile,假设你在各个模型中有这种关系。您的延迟加载查询已经获取了Authenticated User的配置文件,因此该命令不会创建第二个查询(由于雄辩)。

+0

嗨,谢谢你的回答,非常有意义我真的认为你的问题解决了。然而,我仍然得到相同的错误:试图获得非对象的属性 – user1543871 2013-05-12 00:06:03

+0

我的歉意,我没有浏览你的刀片语法,我编辑了我的答案,它现在应该完全解决问题。 :) – 2013-05-12 00:50:41

+0

好的非常感谢您的帮助,我会检查我的代码,看看我如何继续。 – user1543871 2013-05-12 15:31:25