Laravel: getting an array inside an objet bei joinig two tables - laravel

I have two tables: films and actors. Thy have a n-m relation.
I have a connection table actor_film with two columns film_id and actor_id.
In order to get the list of films added in the current month with the actors that play in each film I did this:
$current_month_film = DB::table('films')
->join('actor_film', 'actor_film.film_id', '=', 'films.id')
->join('actors', 'actors.id', '=', 'actor_film.actor_id')
->select('films.*', 'actors.name as actors_name')
->whereMonth('films.created_at', '=', Carbon::now()->month)
->orderBy('films.created_at', 'desc')
->groupBy('films.name')
->get();
return view('statistics.month')->withCurrent_month_film($current_month_film);
I get 40 films each of it showing just ONE actor, even if I know there are several actors in one film.
If I delete the "->groupBy('films.name')" I get 132 record: one film several times and each time one actor.
How could I get a list of actors inside each film, joinig the two tables? something like:
[
{
film.id: 1,
film.name,
film.actors
{
actor[1].name: Morgan Freeman,
actor.[2].name: Meryl Streep
actor [n].name: ....
}
},
{
film.id: 2,
film.name,
film.actors
{
actor[1].name: Morgan Freeman,
actor.[2].name: Meryl Streep
actor [n].name: ....
}
}
]

If you want to use Eloquent and you have your relation in place then your can do it as:
Film::whereMonth('created_at', Carbon::now()->month)
->orderBy('created_at', 'desc')
->with(['actors' => function($q) {
$q->select('name');
}])
->get()
Docs

As you're using Laravel, you should make the use of Laravel Relationships. You should have a models like this:
class Actor extends Model
{
public function films() {
return $this->belongsToMany(Film::class, 'actor_film');
}
}
class Film extends Model
{
public function actors() {
return $this->belongsToMany(Actor::class, 'actor_film');
}
}
and to get the film with their respective actors, you can use with method like this:
$films = Film::with(['actors' => function($q) {
$q->select('name');
}])
->whereMonth('created_at', Carbon::now()->month)
->orderBy('created_at', 'desc')
->get();
foreach($films as $film) {
$film_name = $film->name;
$actors_arr = $film->actors->toArray();
}
See more about Laravel's Eloquent Relationships & Eager Loading
Hope this helps!

In Controller
$current_month_film = Film::select('*')->with(['actor_film','actors'])
->whereMonth('films.created_at', '=', Carbon::now()->month)
->orderBy('films.created_at', 'desc')
->groupBy('films.name')
->get();
In App\Model\Film Model
namespace App;
use Illuminate\Database\Eloquent\Model;
class Film extends Model
{
//
protected $primaryKey = "id"; //primary key
protected $table = 'film';
public function actor_film(){
return $this->belongsTo('App\Model\ActorFilm','film_id','id');
}
public function actors(){
return $this->hasMany('App\Model\Actors','id','actor');
}
}

Related

Eloquent `with()` with filtering based on relation

I have this tables.
And this model relations, this relations works fine.
class Item extends Model
{
public function translations()
{
return $this->hasMany(ItemTranslations::class);
}
}
class ItemTranslation extends Model
{
public function language()
{
return $this->belongsTo(Language::class);
}
}
I need to return a list of items with the translations, but only the translations related to a specific language.
I can't have this query working, im getting all translations of each item, not only the one filtered with this query. The language related to the translation is not needed on the result.
$query = Item::query();
$query->with('translations')->when('language',function($query) use ($ISOlanguage) {
return $query->where('languages.ISO_code', '=', $ISOlanguage);
});
return $query->paginate();
Any idea who i can have this working? Thanks!
So what you want to do is constraining eager loading
Item::with(["translations" => function ($query) use ($ISOlanguage) {
$query->where('language.ISO_code', $ISOlanguage);
}])->get();
https://laravel.com/docs/5.8/eloquent-relationships#constraining-eager-loads
I finally have it working
Item::with(['translations' => function($query) use ($ISOlanguage) {
$query->whereHas('language', function($query) use ($ISOlanguage) {
$query->where('ISO_code', '=', $ISOlanguage);
});
}])->get();
Thanks #julian-s for your help!

How get data in method from others tables?

This is my simple db schema. Now in my group table i have 'group_A' and 'group_B'. In questions table i have 10 questions 5 for group_A and 5 for group_B. Users table is one user with ID = 1. What i try to do is get data like this:
SELECT answer
FROM answers
JOIN questions q ON (q.id = answer.question_id)
JOIN group g ON (g.id = q.group_id)
WHERE user_id = 1 AND g = 'group_A'
I have model in users class and i would like create method to get answers depend from group:
public function getAnswers($group) {
return $this->hasMany('App\Answers', 'question_id', 'id');
}
How can i get this in that method ? Should i create method group in questions class ?
Not sure about how to define such relation in model which takes input parameter but you could define a scope in your model to get the answers filtered by group like
class Answer extends Model {
public function user()
{
return $this->belongsTo('App\User');
}
public function question()
{
return $this->belongsTo('App\Question');
}
public function scopeGroup($query, $name)
{
return $query->whereHas('question.group', function($q) use($name){
$q->where('name', '=', $name);
});
}
}
I assume in answers model you have defined relationship for question and similarly in question model you have defined relationship for group model.
In query builder you could write it as
$answers = Answer::group('group_A')
->whereHas('user', function($q) use($userid){
$q->where('id', '=', $userid);
})->get();
Or you could apply filter on eager loaded relations as
$users = User::with(['answers' => function($query)
{
$query->whereHas('question.group', function($q){
$q->where('name', '=', 'group_A');
});
}])->get();
If you already have user object you can get answers for specific group as
$answers = $user->answers()
->whereHas('question.group', function($q){
$q->where('name', '=', 'group_A');
})->get();

Laravel 5.3 eloquent 3 table join using models

I read this post which helped, but need more guidance please.
I need a set of Results for a particular $batteryid (on Result) and a particular $age (on Test model) and a particular $gender (from Athlete). Each Test belongs to one athlete. Each test has many results.
Model Battery:
class Battery extends Model{
public function results(){
return $this->hasMany('App\Result');
}
}
Model Result:
class Result extends Model{
public function test(){
return $this->belongsTo('App\Test', 'test_id');
}
public function battery(){
return $this->belongsTo('App\Battery', 'battery_id');
}
}
Model Test:
class Test extends Model{
public function athlete(){
return $this->belongsTo('App\Athlete', 'athlete_id');
}
public function results(){
return $this->hasMany('App\Result');
}
}
I get the correct results with the following, but it's two queries:
$tests = Test::whereHas('Athlete', function($query) use($gender){
$query->wheregender($gender);
})->where('age', $age)->get();
$test_ids = $tests->pluck('id');
$results = Result::where('battery_id', '=', $battery)
->whereIn('test_id', $test_ids)
->get();
I'd like to use model approach, but am completely stuck. test.age not recognised and not sure how to get the age from athlete model. My attempt:
$results = Result::with('test')
->where('test.age', '=', $age)
->join('batteries', 'batteries.id', '=', 'test.battery_id')
//->where('test->athlete().gender', '=' $gender)
->where('battery_id', '=', $battery)
->get();
You can use whereHas for the condition and with method for eager loading it.
$results = Result::whereHas('test', function($q) use ($age) {
$q->where('age', '=', $age);
$q->whereHas('athlete', function ($q) {
$q->where('gender', 'male');
});
})
->with('test')
->whereHas('battery', function($q) use($battery) {
$q->where('battery_id', '=', $battery);
})
->with('battery')
->get();

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.

Eloquent where condition based on a "belongs to" relationship

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);

Resources