繁体   English   中英

Laravel Eloquent Inaccessible by $ 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 }}给出:

试图获得非对象的属性

当呼叫{{ $conversation->sender }}它只打印“4”(id)。

发件人存储在名为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的主键,你也可以删除它)

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM