Eloquent where condition based on a "belongs to" relationship - laravel

Let's say I have the following model:
class Movie extends Eloquent
{
public function director()
{
return $this->belongsTo('Director');
}
}
Now I'd like fetch movies using a where condition that's based on a column from the directors table.
Is there a way to achieve this? Couldn't find any documentation on conditions based on a belongs to relationship.

You may try this (Check Querying Relations on Laravel website):
$movies = Movie::whereHas('director', function($q) {
$q->where('name', 'great');
})->get();
Also if you reverse the query like:
$directorsWithMovies = Director::with('movies')->where('name', 'great')->get();
// Access the movies collection
$movies = $directorsWithMovies->movies;
For this you need to declare a hasmany relationship in your Director model:
public function movies()
{
return $this->hasMany('Movie');
}
If you want to pass a variable into function($q) { //$variable } then
function($q) use ($variable) { //$variable }

whereBelongsTo()
For new versions of Laravel you can use whereBelongsTo().
It will look something like this:
$director = Director::find(1);
$movies = Movie::whereBelongsTo($director);
More in the docs.
is()
For one-to-one relations is() can be used.
$director = Director::find(1);
$movie = Movie::find(1);
$movie->director()->is($director);

Related

The equivalence of the AND statement in a ON statement (JOIN) in EloquentORM

Take a look at the query below:
SELECT v*, s.*
FROM videos v
INNER JOIN subtitles s ON (s.subtitle_id = v.video_id AND s.language = 'en')
WHERE v.video_id = 1000
I want to find the equivalent data retrieval action for a Laravel / Eloquent ORM environment.
So, my options are:
using the DB facade
using the query builder
defining the relationship in the Video model
Let's say I wish to use the latter (if possible).
namespace App\Models\v1;
use App\Models\v1\Subtitles;
use Illuminate\Database\Eloquent\Model;
class Video extends Model
{
protected $table = 'videos';
public function subtitle()
{
return $this->hasOne(Subtitles::class, 'subtitle_id', 'video_id'); // How can I define the AND s.language = 'en' ?
}
}
The problem here is that I don't know how to define the AND s.language = 'en' in EloquentORM.
Any help is appreciated.
You can add a where clause to the relationship:
public function subtitle()
{
return $this->hasOne(Subtitles::class, 'subtitle_id', 'video_id')->whereLanguage('en');
}
Retrieving the model:
Provided you changed your primaryKey property on the video model:
protected $primaryKey = 'video_id';
Docs
You can do the following:
$video = Video::findOrFail(1000);
$subtitle = $video->subtitle;
You can define the relationship and then use whereHas
public function subtitle()
{
return $this->hasOne(Subtitles::class, 'subtitle_id', 'video_id');
}
And then filter it like this
$video = Video::where('video_id', 1000)->whereHas('subtitle', function($query){
$query->where('language', 'en');
})->first();
For details check the doc
If you just want to use join then you can use it like this
$lang = 'en';
$video = Video::where('video_id', 1000)
->join('subtitles', function ($join) use ($lang){
$join->on(function ($query) use ($lang) {
$query->on('subtitles.subtitle_id', '=', 'videos.video_id');
$query->on('subtitles.language', '=', DB::raw($lang));
});
})->first();
Check laravel join

Laravel eloquent get data from two tables

Laravel Eloquent Query builder problem
Hello I have a problem when I am trying to get all the rows where slug = $slug.
I will explain in more details:
I have two tables, cards and card_categories.
cards has category_id.
card_categories has slug.
What I need is a query which returns all the cards which contents the slugs.
For example I made this:
$cards = Card::leftJoin('card_categories', 'cards.id', '=', 'card_categories.id')
->select('cards.*', 'card_categories.*')
->where('card_categories.slug', $slug)
->paginate(5);
But what happens is that just return 1 row per category.
I don't know what is wrong.
Many thanks.
I think I understand what you mean, from your explanation I would imagine your card model is as follows.
class Card extends Model {
protected $table = 'cards';
public function category()
{
return $this->belongsTo(Category::class)
}
}
In which case, you should just be able to do this:
$cards = Card::whereHas('category', function ($query) use ($slug) {
$query->where('slug', $slug);
})->paginate(5);
That will select all of the cards that has the category id of the given slug.

Laravel Eloquent get all categories of restaurants?

I'm trying to get all categories of restaurants.
My models:
Restaurant
public function categories()
{
return $this->belongsToMany(Category::class,'restaurant_categories_relation','restaurant_id');
}
Category
public function restaurants()
{
return $this->belongsToMany(Restaurant::class,'restaurant_categories_relation', 'category_id');
}
In my controller:
$restaurants = Restaurant::where('district_id', $request->district)->paginate(8);
$categories = $restaurants-> ????;
Please help me do this, thanks!
You could use has() like :
Category::has('restaurants')->get();
That will return the categories who are related with the restaurants.
Try also the use of whereHas like :
$users = Category::whereHas('restaurants', function($q){
$q->->where('district_id', $request->district)->paginate(8);
})->get();
Since you've already a Collection we can't query the categories so I suggest adding a function to scope that inside the Restaurant model like :
public static function getCategoriesOfRestaurants($restaurants)
$categories = [];
foreach($restaurants as $restaurant){
array_push( $categories, $restaurant->categories->pluck('id')->toArray());
}
return Category::WhereIn('id', array_unique($categories))->get();
}
Then just call it when you get the $restaurants collection :
$restaurants = Restaurant::with("categories")->where('district_id', $request->district)->paginate(8);
$categories = Restaurant::getCategoriesOfRestaurants($restaurants);
Note: The use of with("categories") when getting the collection will query All the related categories in the first query so the foreach loop will not generate any extra query just looping through the already fetched data, and finally we will get the collection of categories in the return statement.
use with() method for eagerloading, that provides you get all categories in a single query
$restaurants = Restaurant::with("categories")->where('district_id', $request->district)->paginate(8);
foreach($restaurants as $restaurant){
foreach($restaurant->categories as $category)
{{$category}}
}
}
if you want to use categories outside of the loop, then assign these categories to a variable
foreach($restaurants as $restaurant){
$categories = $restaurant->categories;
}
// do something with $categories
Your relation should be
Restruant.php
public function categories() {
return $this->belongsToMany(Category::class,'restaurant_categories_relation','restaurant_id','category_id');
}
then in you controller method just wirte
$restruants = Restruant::with('categories')->get();
It should return you collection of all restruants with all related categories.

Laravel 4 Eloquent Two Pivot Table

My tables
Modelos
id
nome slug
marca_id
Pecas
id
codigo
modelo_peca
modelo_id
peca_id
produtos
id
categoria_id
codigo
nome
categorias
id
nome
slug
I have these models
class Modelo extends Eloquent
{
public function pecas()
{
return $this->belongsToMany('Peca');
}
}
class Peca extends Eloquent {
public function modelos()
{
return $this->belongsToMany('Modelo');
}
public function produtos()
{
return $this->belongsToMany('Produto');
}
}
class Produto extends Eloquent {
public function pecas()
{
return $this->belongsToMany('Peca');
}
}
I´m trying to create a route that pass all the products related to a modelo to a view. What´s wrong?
Route::get('/modelo/{slug?}', function($slug = null) {
if ($slug) {
$id = Modelo::where('slug', $slug)->pluck('id');
$pecas = Modelo::find($id)->pecas;
$produtos = Peca::where('id', $pecas)->get();
}
return View::make('produto.home')->with('produtos', $produtos);
Use eager loading
Off the top of my head (also across the language barrier I'll do my best)
You seem to want all Products (produtos) for a specific page category other taxonomy (may be wrong but you can adjust the code as needed)
The where() method expects three parameters iirc so instead the first query would be $id = Modelo::where('slug', '=', $slug)->pluck('id');
The same would apply to the other where statements.
Full query:
if($slug)
{
$query = Modelo::with('pecas.produto')
->where('slug', '=', $slug)
->get();
$produtos = $query->produto;
}
return View::make('produto.home')->with('produtos', $produtos);
Here I've taken a different approach and eager loaded the relations, I'm not 100 percent sure this is how you want this to be done but it hopefully gives you a foundation for using your relations properly in Eloquent.
You don't need to manually get primary keys and perform multiple queries, check out the Eloquent documentation on the Laravel website.

Laravel: Querying and accessing child objects in nested relationship with where clauses

I am trying to access the child objects of nested relationships that return many results from the parents object.
Let's say I have 4 models : Country - Provinces - Cities - Municipalities
Their relationships are as follows :
Country Model
class Country extends Eloquent
{
protected $table = 'countries';
public function provinces()
{
return $this->hasMany('Province');
}
}
Province Model
class Province extends Eloquent
{
protected $table = 'provinces';
public function cities()
{
return $this->hasMany('City');
}
public function country()
{
return $this->belongsTo('Country');
}
}
City Model
class City extends Eloquent
{
protected $table = 'cities';
public function municipalities()
{
return $this->hasMany('Municipality');
}
public function province()
{
return $this->belongsTo('Province');
}
}
Municipality Model
class Municipality extends Eloquent
{
protected $table = 'municipalities';
public function cities()
{
return $this->belongsTo('City');
}
}
Now what I am trying to do is get all municipalities in a given country that have a population over 9000 and are located in provinces that are considered West.
So far I have something like this :
$country_id = 1;
$country = Country::whereHas('provinces', function($query){
$query->where('location', 'West');
$query->whereHas('cities', function($query){
$query->whereHas('municipalities', function($query){
$query->where('population', '>', 9000);
});
});
})->find($country_id);
Now I can easily get the provinces with $country->provinces but I can't go any deeper than that.
EDIT1 : Fixing the belongsTo relationship as noticed by Jarek.
EDIT2: In addition to Jarek's answer, I wanted to share what I also found however Jarek's is probably the more proper method.
Instead of trying to go from top to bottom (Country -> Municipality) I decided to try the other way (Municipality -> Country) Here's how it works (and I tested it, also works)
$municipalities = Municipality::where('population', '>', 9000)
->whereHas('city', function($q) use ($country_id){
$q->whereHas('province', function($q) use ($country_id){
$q->where('location', 'West');
$q->whereHas('country', function($q) use ($country_id){
$q->where('id', $country_id);
});
});
})->get();
I have no idea if this is an actual proper way or if performance would be accepted but it seemed to do the trick for me however Jarek's answer looks more elegant.
Your Municipality-City is probably belongsTo, not hasMany like in the paste.
Anyway you can use hasManyThrough relation to access far related collection:
Country - City
Province - Municipality
Unfortunately there is no relation for 3 level nesting, so you can't do this just like that.
Next, your code with whereHas does not limit provinces to west and municipalities to 9000+, but only limits countries to those, that are related to them. In your case this means that result will be either Country (if its relations match these requirements) or null otherwise.
So if you really want to limit related collections, then you need this piece:
$country = Country::with(['provinces' => function($query){
$query->where('location', 'West');
}, 'provinces.cities.municipalities' => function ($query){
$query->where('population', '>', 9000);
}])->find($country_id);
This is applying eager loading constraints, and what it does is:
1. loads only West provinces for country with id 1
2. loads all the cities in these provinces
3. loads only 9k+ municipalities in these cities
Since you're not interested in cities, you could use hasManyThrough on the Province:
// Province model
public function municipalities()
{
return $this->hasManyThrough('Municipality', 'City');
}
then:
$country = Country::with(['provinces' => function($query){
$query->where('location', 'West');
}, 'provinces.municipalities' => function ($query){
$query->where('population', '>', 9000);
}])->find($country_id);
However in both cases you can't access the municipalities directly, but only like this:
// 1 classic
$country->provinces->first()->cities->first()->municipalities;
// 2 hasManyThrough
$country->provinces->first()->municipalities;
That being said, if you'd like to work with all those municipalities, you need this trick:
$country = Country::with(['provinces' => function($query){
$query->where('location', 'West');
}, 'provinces.municipalities' => function ($query) use (&$municipalities) {
// notice $municipalities is passed by reference to the closure
// and the $query is executed using ->get()
$municipalities = $query->where('population', '>', 9000)->get();
}])->find($country_id);
This will run additional query, but now all the municipalities are in single, flat collection, so it is very easy to work with. Otherwise you likely end up with a bunch of foreach loops.

Resources