在表Laravel之间创建连接

时间:2018-01-22 13:14:17

标签: laravel join

我有2张桌子:帖子 - 评论

我希望在这两个表之间建立关系,并且需要更新具有“1”Post_ID的注释:

路线:

  

Route :: get('join','JoinController @ Join');

控制器:

public function Join()
{
    $Comment = Posts::find(1)->Comment;
    $Comment->Title = "JOIN";
    $Comment->save();
}

帖子型号:

public function Comment()
{
    return $this->hasOne('App\Comment');
}

评论模型:

public function Posts()
{
    return $this->belongsTo('App\Posts');
}

但是我收到了这个错误:

  

尝试获取非对象的属性

2 个答案:

答案 0 :(得分:0)

请改为:

$comment = new Comment;
$comment->Title = 'JOIN';
#comment->post_id = 1;
$comment->save();

或者您可以使用create()方法:

$Comment = Posts::find(1)->Comment()->create(['Title' => 'JOIN']);

如果您使用create()方法,请确保Title数组中包含$fillable

答案 1 :(得分:0)

$Comment = Posts::find(1)->Comment()->first();
$Comment->Title = "JOIN";
$Comment->save();
相关问题