当访问特定的url时,我不理解返回用户创建的帖子的代码。我有两个疑问。
首先,您知道$username变量是如何存在于“if($username = request('createdBy')){”中的吗?就在它显示出未定义之前。
另一个疑问是,您知道$posts = $posts-get();,如果用户访问“http://proj.test/posts?createdBy=john”,如何只返回用户创建的帖子(这是应该的),而不是所有用户的所有帖子?因为在if(username = request(createdBy))内部,$posts变量不会被一个新值过写,所以$posts值不应该显示所有用户的所有帖子?
public function index(Category $category)
{
if($category->exists){
$posts = $category->posts()->latest();
}else{
$posts = Post::latest();
}
dd($username); // shows Undefined variable: username
if($username = request('createdBy')){
dd($username); // shows john if the url is "http://proj.test/posts?createdBy=john"
$user = User::where('name', '=', $username)->first();
$posts->where('user_id','=', $user->id);
}
$posts = $posts->get();
return view('posts.index', compact(('posts')));
}发布于 2018-11-01 15:46:31
=是一个赋值运算符。$username被赋值,然后if检查$username的值是否真实。
没有理由在条件块中重新分配$post的值。$post是一个查询生成器对象,而$post->where()正在对该对象进行变异。
我建议您阅读PHP手册中的运算符和对象。
https://stackoverflow.com/questions/53104263
复制相似问题