Laravel Eloquent在连接表上的位置 [英] Laravel Eloquent where on Join Table

查看:36
本文介绍了Laravel Eloquent在连接表上的位置的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在laravel 5 Eloquent中有两个实体,Foo和FooType具有oneToMany关系.

I have two entities in laravel 5 Eloquent, Foo and FooType with oneToMany relation.

class Foo {

   public function fooTypes(){
    return $this->hasMany('App\FooType');
   }
}

和FooType

class FooType{

   public function foo(){
     return $this->belongsTo('App\Foo');
   }
}

问题1:我该如何使用雄辩的查询生成器进行查询并返回具有 type_id (此列在FooType表中)为5的Foos;

question 1: how can I query using eloquent query builder and return Foos that has type_id(this column is in FooType table) of 5;

我尝试过的事情:

Foo::fooTypes()->where('type_id', 5);

以及有关此类查询的良好链接的任何链接.

and any link for good tuts about queries like this.

问题二:我发现这很难使用.雄辩的查询生成器是否是与普通laravel查询结合使用的不好的做法DB,我的意思是,使用db不能使用orm或类似的东西(或使用雄辩的查询生成器有什么好处):

question two: I find out this is hard to use Eloquent query builder is it bad practice to use normal laravel queries with DB, I mean by using db I cannot use orm or something like that(or what is the benefits of using eloquent query builder):

$foos = DB::table('foos')
        ->join('fooTypes', 'foo_id', '=', 'foos.id')
        ->where('fooTypes.type_id', '=', '5')
        ->select('foos.*')
        ->get();

这种查询非常容易,并且有更多关于它的教程.

this type of queries are much easy and there more tutorials about it.

推荐答案

问题1的答案:
您可以在使用雄辩的orm时使用advance where子句,例如可以使用:

Answer to Question 1:
You can use advance where clause when using eloquent orm like in your case, use can try:

Foo::whereHas('fooTypes', function($query){
    $query->whereTypeId(5);  
})->get();  

问题2的答案:

数据映射器"或查询"构建器比"ORM活动记录"更快.因此,当您编写具有大量并发请求的大型应用程序时,Data Mapper/Query Builder是您的理想之选.

Data Mapper or Query builder is faster than ORM Active Record. So when you are writing very large applications with significant number of concurrent requests then Data Mapper / Query Builder is the way to go.

另一方面,ORM为刚开始使用Laravel或正在编写小型或中型应用程序的人提供了更简洁的语法和更好的代码可读性,而并发请求的数量不会很大.

On the other hand ORM provides a much cleaner syntax and better code readability for someone who just started with Laravel or is writing small or medium size app where the number of concurrent requests will not be significantly large.

Query Builder语法更接近于普通的SQL查询,使用数据库和sql的任何人都发现它很容易与之联系.
因此,您必须根据自己对查询"构建器语法的舒适程度以及所编写的应用程序的大小来进行选择.

Query Builder syntax is nearer to the plain SQL queries, which anyone who has worked with databases and sql finds easy to relate to.
So its a choice you have to make depending your comfort with the Query builder syntax as well as the size of app you are writing.

Laravel Eloquent vs Fluent查询构建器

这篇关于Laravel Eloquent在连接表上的位置的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆