2015-01-05 61 views
0

我已經做過很多次,但不知何故我的心是停留在這一個:

$data['conversations'] = Conversation::with("sender")->received()->get(); 

{{ $conversation }}產生:

{ 
    "id": "1", 
    "subject": "", 
    "sender": { 
     "id": "4", 
     "email": "[email protected]", 
     "name": "Jane Poe", 
     "group_id": "3", 
     "created_at": "2014-12-22 20:31:00", 
     "updated_at": "2014-12-22 20:31:00" 
    }, 
    "receiver": "1", 
    "created_at": "2015-01-04 00:00:00", 
    "updated_at": "2015-01-04 00:00:00" 
} 

注意,「發件人現在{{ $conversation->sender->email }}給出:

試圖獲得非物件的財產

當致電{{ $conversation->sender }}時,它僅打印「4」(id)。

發件人存儲在對話中表中列名爲發件人

$conversation->sender()沒有工作,要麼

這是代碼:

class Conversation extends Eloquent { 

    protected $table = 'conversations'; 

    public function sender() 
    { 
     return $this->belongsTo('User','sender','id'); 
    } 

    public function receiver() 
    { 
     return $this->belongsTo('User','receiver','id'); 
    } 

} 

回答

3

的關係,不能有同名的外鍵(或基本上任何列)

只需將sender更改爲sender_id即可。那麼你甚至可以將它從關係聲明中刪除,因爲它是傳統的命名。

public function sender() 
{ 
    return $this->belongsTo('User'); 
} 

(而且因爲id大概是User主鍵,你可以刪除以及)