简体   繁体   English

使用Laravel雄辩关系查询有什么优势?

[英]What's the advantage of using Laravel Eloquent Relationship queries?

So I'm trying to improve my queries by implementing eloquent relationships. 因此,我试图通过实现雄辩的关系来改善查询。 Let's say I have a threads table and each thread have replies 假设我有一个线程表,每个线程都有回复

What I need is a JSON object of the information of threads with array of all the replies. 我需要的是一个带有所有答复数组的线程信息的JSON对象。

Currently, I can achieve what I want with this. 目前,我可以实现此目标。

public function show($threadId){
        $threads = ThreadView::find($threadId);
        $threads->replies = ReplyView::where('threadId', $threadId)->get();
        return response()->json($threads, 200);
    }

With eloquent relationship, I can achieve the same result with something like this. 通过雄辩的关系,我可以通过类似的事情达到相同的结果。

public function show($threadId) {

    $threads= ThreadView::find($threadId);
    $threads->replies= ThreadView::find($threadId)->Replies;

    return response()->json($threads, 200);
}

Is there an advantage to using relationship? 使用关系有优势吗? They both look the same to me. 他们对我来说都一样。

Using Eloquent you can do this even shorter: 使用Eloquent,您可以执行以下操作:

public function show($threadId) {
    $threads = ThreadView::with('replies')->find($threadId);
    return response()->json($threads, 200);
}

The with function will eager load relations without you having to write the query. with函数将渴望加载关系,而无需编写查询。

That is the advantage of Eloquent, it writes the queries for you. 这是Eloquent的优势,它为您编写查询。 No need to create join queries or extra queries for you. 无需为您创建联接查询或其他查询。

public function show($threadId) {

    $threads= ThreadView::with('replies')->find($threadId);

    return response()->json($threads, 200);
}

The main advantage is that using relationships like this, the first example does 2 selects (it grabs 100% of ThreadView then 100% of ReplyView ), while the second example only does 1 query. 主要优点是使用这样的关系,第一个示例执行2个选择(它获取100%的ThreadView然后获取100%的ReplyView ),而第二个示例仅执行1个查询。

The second advantage is that Eloquent does a Really Good Job at lazy loading compared to others and it is much better to use if you are not an expert in SQL queries. 第二个优点是,与其他语言相比,Eloquent在延迟加载方面做得非常好,如果您不是SQL查询方面的专家,则更好用。

Ditching Eloquent models and using the DB Builder directly will be approximately 500x faster, and I find the code cleaner. 放弃Eloquent模型并直接使用DB Builder的速度大约快500倍,我发现代码更简洁。 That may be what you're looking for. 那可能就是您要寻找的。

But if you use models, use the relationships! 但是,如果您使用模型,请使用关系!

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM