当我只有帖子表中的用户名时,我想从用户表中获取用户头像。
我尝试过这样的foreach循环:
$posts = Post:all();
foreach($posts as $post) {
$user = User::where('name', $post->creator)->get();
}
return view('welcome')->with('posts', $posts)->with('user', $user);
然后在我的视图中将其循环如下:
@foreach($posts as $post)
@foreach($user as $creator)
<span>{{ $creator->avatar }}</span>
<span>{{ $post->post_url }}</span>
@endforeach
@endforeach
但是它返回的是相同的头像图片,而不是属于该帖子的用户的头像图片。
我的用户模型:
protected $fillable = [
'name', 'email', 'password', 'avatar', 'full_name', 'slug'
];
/**
* The attributes that should be hidden for arrays.
*
* @var array
*/
protected $hidden = [
'password', 'remember_token',
];
/**
* The attributes that should be cast to native types.
*
* @var array
*/
protected $casts = [
'email_verified_at' => 'datetime',
];
public function posts() {
return $this->hasMany(Post::class, 'creator','name');
}
发布模型:
protected $fillable = [
'creator', 'post_url', 'game', 'likes', 'created_at'
];
public function user() {
return $this->belongsTo(User::class);
}
我的web.php:
Route::get('/', 'PostController@main_page');
我的函数main_page:
public function main_page()
{
$posts = Post:all();
foreach($posts as $post) {
$user = User::where('name', $post->creator)->get();
}
return view('welcome')->with('posts', $posts)->with('user', $user);
}
有人可以启发我,把我带到正确的道路吗?谢谢!
答案 0 :(得分:1)
您为每个帖子覆盖$user
变量。而是将其保存在数组中:
$posts = Post::all();
$users = [];
foreach($posts as $post) {
$users[$post->id] = User::where('name', $post->creator)->get();
}
return view('welcome')->with('posts', $posts)->with('users', $users);
然后在视图中:
@foreach($posts as $post)
<span>{{ $users[$post->id]->avatar }}</span>
<span>{{ $post->post_url }}</span>
@endforeach
但是更好的解决方案是将用户的id
保存在posts
表中,而不仅仅是名称和add a relationship。那么代码将是:
$posts = Post::with('user')->get();
return view('welcome')->with('posts', $posts);
with('user')
preloads the relationship,以免生成太多查询。如果您只需要头像,则可以使用with('user:avatar')
来使其表现更好。
该视图将如下所示:
@foreach($posts as $post)
<span>{{ $post->user->avatar }}</span>
<span>{{ $post->post_url }}</span>
@endforeach
答案 1 :(得分:0)
如果您知道sql,则可以将类似以下内容的内容发送到数据库:
SELECT avatar FROM users WHERE username="John_15";
答案 2 :(得分:0)
首先,这种方法会导致性能和逻辑问题..最好替换用id标识用户名或确保名称唯一的想法。.但这是解决方法
luigi.WrapperTask
我建议根据外键在用户和帖子之间建立联系