首页 > 解决方案 > 从其他表 laravel 中获取价值

问题描述

我想从 role_id=2 的用户表中获取价值

public function index(){
         return view('admin.articles.index',[
        'articles' => Article::orderBy('created_at', 'desc')->paginate(10),
        'articles_suggest' => Article::with('user')->where('user.role_id',2)->paginate(10),
    ]);

}

 Unknown column 'user.role_id' in 'where clause' (SQL: select count(*) as aggregate from `articles` where `user`.`role_id

用户模型

public function articles(){
        return $this->hasMany('App\Article');
    }

文章模型

 public function user(){
    return $this->belongsTo(User::class, 'author_id');
  }

标签: phplaravel

解决方案


首先,我会看一下@deepak 评论。这是一个关于Eager loading的链接。重写 index 函数,如下所示:

$articles = Article::with(['user' => function ($query) {
    $query->where('role_id', '=', 2);
}])->paginate(10);

然后,我想你可以在你的视图中这样做:

// Looping through articles
@foreach($articles as $article)
    // Check if there is a user associated with the article
    @if( $article->user )
        // Access the user column/attribute
        {{ $article->user->theusercolumn }}
    @endif
@endforeach

推荐阅读