[英]How To use Eloquent in From One Model to another model through intermediate table
我有三种模式
文章
id
title
评论
id
title
user_id
article_id
用户
id
name
我要实现的是根据带有评论的用户ID和发表该评论的用户信息选择一篇文章
像那样 :
$article = Article::find($id -- say 1)->with('comments' -- this is a relation in Article Model)->get();
这给了我带有相关注释的文章,作为一组对象说注释一-注释二,等等...。
我想要代替注释对象中的user_id的内容,我想成为用户对象
看到这张照片就是我到目前为止所达到的
使用laravel 5.4
您可以使用以下内容:
$articles = Article::find($id)->with('comments', 'comments.user')->get();
这里的“用户”是您在用户的评论模型中提到的关系。
如果您已在模式中定义了外键关系,则可以按照以下参考链接-Laravel-口才关系中定义的口才关系定义函数。
您可以按以下方式在模型中定义函数-
文章-
class Article extends Model
{
...
public function comments(){
// Accessing comments posted to that article.
return $this->hasMany(\App\Comment::class);
}
// Create a foreign key to refer the user who created the article. I've referred it here as 'created_by'. That would keep relationship circle complete. You may ignore it if you want.
public define user(){
// Accessing user who posted the article
return $this->hasOne(\App\User::class, 'id', 'created_by');
}
}
评论-
class Comment extends Model
{
...
public function article(){
// Accessing article to which the particular comment was posted
return $this->hasOne(\App\Article::class, 'id', 'article_id');
}
public function user(){
// Accessing user who posted the comment
return $this->hasOne(\App\User::class, 'id', 'user_id');
}
}
用户-
class User extends Models
{
...
public function articles(){
// Accessing articles posted by a user
return $this->hasMany(\App\Article::class);
}
public function comments(){
// Accessing comments posted by a user
return $this->hasMany(\App\Comment::class);
}
}
现在,您可以像下面这样使用-
$article = Article::findOrFail($id);
$comments = $article->comments;
$article_user = $article->user;
$comment_user = Comment::findOrFail($commnet_id)->user;
$users_comments = User::findOrFail($user_id)->comments;
$users_articles = User::findOrFail($user_id)->articles;
等等...
最后最好使用-> find()而不是-> get(),因为get()返回一个Collection。
这样,您将获得所需的单个对象,而不是Collection。
例如:
$commentableObj = Post::with(['comments'])
->withCount(['comments'])
->findOrFail($commentable->id);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.