php - 在非对象错误上雄辩的attach()

原文 标签 php laravel-4 eloquent

Eloquent attach() on a non-object error

I am trying to attach a message to a conversation (many-to-many), but I am getting an error. What am I missing?

Pivot Table Schema

conversation_message (conversation_id, message_id)

Models

class Conversation extends Eloquent
{
    public function messages()
    {
        $this->belongsToMany('Message', 'conversation_message', 'conversation_id', 'message_id');
    }
}

class Message extends Eloquent
{
    public function conversations()
    {
        $this->belongsToMany('Conversation', 'conversation_message', 'message_id', 'conversation_id');
    }
}

Controller

$conversation = Conversation::find(1);
$message = Message::find(1);
$conversation->messages()->attach($message);

Error

Call to a member function attach() on a non-object
Answer

There are returns missing in both methods:

class Conversation extends Eloquent
{
    public function messages()
    {
        return $this->belongsToMany('Message', 'conversation_message', 'conversation_id', 'message_id');
    }
}

class Message extends Eloquent
{
    public function conversations()
    {
        return $this->belongsToMany('Conversation', 'conversation_message', 'message_id', 'conversation_id');
    }
}

翻译

我正在尝试将消息附加到对话(多对多),但出现错误。我想念什么?

数据透视表架构

conversation_message(conversation_idmessage_id)

楷模

class Conversation extends Eloquent
{
    public function messages()
    {
        $this->belongsToMany('Message', 'conversation_message', 'conversation_id', 'message_id');
    }
}

class Message extends Eloquent
{
    public function conversations()
    {
        $this->belongsToMany('Conversation', 'conversation_message', 'message_id', 'conversation_id');
    }
}


控制者

$conversation = Conversation::find(1);
$message = Message::find(1);
$conversation->messages()->attach($message);


错误

Call to a member function attach() on a non-object
最佳答案
两种方法都缺少return:

class Conversation extends Eloquent
{
    public function messages()
    {
        return $this->belongsToMany('Message', 'conversation_message', 'conversation_id', 'message_id');
    }
}

class Message extends Eloquent
{
    public function conversations()
    {
        return $this->belongsToMany('Conversation', 'conversation_message', 'message_id', 'conversation_id');
    }
}
相关推荐

php - 按距离对邮政编码邻近搜索进行排序(php / mysql)

php - PHP类常量和php函数常量给出警告

php - Symfony DomCrawler状态代码不起作用?

php - 使用foreach循环删除建立SQL查询中的最后一个“ UNION ALL”

php - 基于时间的PHP问候

php - Laravel雄辩的ORM-save()返回未找到的列(MySQL错误)

php - f3框架sql查询联接

php - PHP Regex:匹配字符集或字符串结尾

php - PHP / MySQL平均基于数组的内容

php - 如何使用PHP将图像发送到deviantsart rest API