您想要研究多态关系来解决这个问题.您希望能够对帖子和评论发表评论.
我所做的是设置一个可评论的特性,并让我想添加注释的模型使用它.这样,如果您想要评论另一个模型,您只需将该特征添加到该模型即可.
Laracasts是laravel的一个很好的资源,并且对特性有很好的教训.
还有一点比这更多,但希望它会让你开始.
您可以像这样设置数据库结构.
用户表
`id` int(10),
`name` varchar(255),
`username` varchar(255)
Run Code Online (Sandbox Code Playgroud)
评论表
`id` int(10),
`user_id` int(10),
`body` text,
`commentable_id` int(10),
`commentable_type` varchar(255)
Run Code Online (Sandbox Code Playgroud)
帖子表
`id` int(10),
`user_id` int(10),
`body` text
Run Code Online (Sandbox Code Playgroud)
你的模特是这样的.
评论模型
<?php namespace App;
use Illuminate\Database\Eloquent\Model;
class Comment extends Model {
use CommentableTrait;
/**
* Get all of the owning commentable models.
*/
public function commentable()
{
return $this->morphTo();
}
public function user()
{
return $this->belongsTo('App\User');
}
}
Run Code Online (Sandbox Code Playgroud)
发布模型
<?php namespace App;
use CommentableTrait;
use Illuminate\Database\Eloquent\Model;
class Post extends Model {
use CommentableTrait;
}
Run Code Online (Sandbox Code Playgroud)
当然你需要这个特质.
特征
<?php namespace App;
use Comment;
trait CommentableTrait {
/**
* List of users who have favorited this item
* @return \Illuminate\Database\Eloquent\Relations\MorphToMany
*/
public function comments()
{
return $this->morphMany('App\Comments\Comment', 'commentable')->latest();
}
/**
* @return \Illuminate\Http\RedirectResponse
*/
public function addComment($body, $user_id)
{
$comment = new Comment();
$comment->body = $body;
$comment->user_id = $user_id;
$this->comments()->save($comment);
return $comment;
}
}
Run Code Online (Sandbox Code Playgroud)