[英]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.