Reputation: 2108
I have two entities in laravel 5 Eloquent, Foo and FooType with oneToMany relation.
class Foo {
public function fooTypes(){
return $this->hasMany('App\FooType');
}
}
and FooType
class FooType{
public function foo(){
return $this->belongsTo('App\Foo');
}
}
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;
something I tried:
Foo::fooTypes()->where('type_id', 5);
and any link for good tuts about queries like this.
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.
Upvotes: 5
Views: 24843
Reputation: 12835
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();
Answer to Question 2:
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.
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 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 query builder
Upvotes: 14