Laravel雄辩vs查询生成器-最佳编码方法 [英] Laravel eloquent vs query builder - best coding approach
问题描述
我已经阅读了很多有关该主题的文章和帖子,但我仍然不确定什么是最好的前进方式.我知道QB更快,有时在代码中没有那么明确.
I have read a lot of articles and posts on the subject and I am still not sure what is the best way forward. I know that QB is faster and sometimes less explicite in the code.
但是我发现,更容易获得雄辩的相关领域的方法比QB更复杂.您有什么建议?
However I found that the easier way to get related field in eloquent is more complicated than QB. What do you recommend?
模型发布
public function article()
{
return $this->belongsTo(Article::class);
}
public function user()
{
return $this->belongsTo(User::class);
}
CONTROLLER PostController
CONTROLLER PostController
$posts = Post::orderBy($sortField,$sortOrder)
->get();
foreach ($posts as $post) {
$post->article = $post->article()->pluck('title')[0];
$post->user = $post->user()->pluck('name')[0];
}
OR
$users = DB::table('posts')
->join('articles', 'articles.id', '=', 'posts.user_id')
->join('users', 'users.id', '=', 'posts.user_id')
->select('users.*', 'articles.title', 'users.name')
->get();
推荐答案
在查询生成器中,使用join并不是一个好主意,将来会降低您的项目速度,只需创建一个简单的查询即可:
In Query Builder, it is not a good idea to use join, in future it will slow your project, just create a simple query:
$posts = Post::orderBy($sortField, $sortOrder)->get();
return view('post', compact('posts'));
并在视图中调用相关表:
And call the related tables in view:
foreach($posts AS $post) {
$article = $post->article;
$user = $post->user;
}
您可以在需要的项目部分使用它.
You can use it in that part of you project that you need.
这篇关于Laravel雄辩vs查询生成器-最佳编码方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!