Laravel Eloquent $model->id 无法访问;

Laravel Eloquent Inaccessible by $model->id;

我以前做过很多次,但不知何故,我的思绪停留在这个问题上:

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

{{ $conversation }} 产生:

{
    "id": "1",
    "subject": "",
    "sender": {
        "id": "4",
        "email": "jane@doe.com",
        "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 }}给出:

Trying to get property of non-object

当调用 {{ $conversation->sender }} 时,它只打印“4”(id)。

sender 存储在 conversation table 中名为 sender.

的列中

$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');
    }

}

关系不能与外键同名(或基本上任何列)

只需将 sender 更改为 sender_id。然后你甚至可以从关系声明中删除它,因为它是常规命名。

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

(因为 id 可能是 User 的主键,你也可以删除它)