php - 从其他表 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');
}
解决方案
首先,我会看一下@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
推荐阅读
- python - 如何在python中不打印数字
- opengl - 是否可以在使用 glBitmap 绘制的位图上使用 glScalef?
- macos - 使用可观察对象帮助定义视图禁用标志时通过属性检测循环
- typescript - 如何从给定的字符串导入打字稿文件?
- java - 通过 prometheus 支持多个指标(statsd 和 prometheus)
- html - 波纹CSS不显示
- python - 在 PyQT5 的 groupbox 中显示 matplotlib 图表
- c++ - 有没有办法在 C++ 中调用没有 () 的函数?
- python-3.x - 如何保证我的异步倒计时功能实时运行?
- reactjs - 收到一个 TypeError: Cannot read property 'map' of undefined in React