Model
Album::join('tracks', 'albums.track_id', '=', 'tracks.id')
->join('singers', 'tracks.singer_id', '=', 'singers.id')->get();
Snigers table
id - int
name - string
Tracks table
id -int
name - string
singers_id - JSON // example["1","2"]
Album table
id - int
name - string
tracks_id - JSON // example ["1","2"]
here first singers table after track table reference array of id multiple and next alums table reference track table id is also array.how to joins this three table
There's no need to use joins here, if you have a pivot table for these, here's what you can simply do:
In your models you can simply create a relation like this:
Album Model:
public function tracks() {
return $this->hasMany(Track::class);
}
public function singers() {
return $this->hasMany(Singer::class);
}
and then call it in your controller.
AlbumController.php
Album::where('id',1)->with('tracks','singers');
This will simply fetch all the records with Tracks and Singers that belong to Album id 1.
Related
So im creating a booking system where you can create maps and assign them to an event. I have 3 tables to handle this, events, maps, and event_maps
I have after reading the Laravel Documentation i decided to set up a belongsToMany relation.
But when i try to retrieve my maps thru my event model i only get one the first row.
in my controller i do
public function displayForm($id)
{
$event = EventModel::find($id);
print_r($event->maps);
}
The result is a Illuminate\Database\Eloquent\Collection Object with the last out of 2 maps, and i can't for my life figger out how to get them all.
My EventsModel
public function maps()
{
return $this->belongsToMany('App\Models\Booky\MapsModel',
// Table name of the relationship's joining table.
'event_maps',
// Foreign key name of the model on which you are defining the relationship
'map_id',
// Foreign key name of the model that you are joining to
'event_id'
);
}
My MapsModel
public function event()
{
return $this->belongsToMany('App\Models\Booky\EventsModel',
// Table name of the relationship's joining table.
'event_maps',
// Foreign key name of the model on which you are defining the relationship
'event_id',
// Foreign key name of the model that you are joining to
'map_id'
);
}
The database looks something like this
events
- id
- lots of irrelevant data
maps
- id
- lots of irrelevant data
event_maps
- id
- event_id
- map_id
I was thinking that perhaps i should use another relation type, but as far as i understand they don't use a relation table like event_maps.
Everything else work as expected.
Anyone who could clear up this mess? :)
The ids are inverted in the relation. Try this:
public function maps()
{
return $this->belongsToMany('App\Models\Booky\MapsModel',
// Table name of the relationship's joining table.
'event_maps',
// Foreign key name of the model that you are joining to
'event_id'
// Foreign key name of the model on which you are defining the relationship
'map_id',
);
}
And:
public function event()
{
return $this->belongsToMany('App\Models\Booky\EventsModel',
// Table name of the relationship's joining table.
'event_maps',
// Foreign key name of the model that you are joining to
'map_id'
// Foreign key name of the model on which you are defining the relationship
'event_id',
);
}
i'm trying to get all the lead_id inside my pivot table but i can't make it work.
controller:
$levels = Level::all();
$levels->lead()->attach('lead_id');
return $levels;
Model Level:
public function lead(){
return $this->belongsToMany(Lead::class, 'level_students')->withPivot('level_id', 'lead_id');
}
Model Lead:
public function level(){
return $this->belongsToMany(Level::class, 'level_students')->withPivot( 'lead_id', 'level_id');
}
If you mean all lead_id of a Level, then you can use pluck().
$level->lead->pluck('lead_id');
I'm not really sure what you are trying to achieve because it seems that you want to retrieve all lead_id associated with any Level. But if that is the case, then you can create a model for the pivot table (e.g. LevelLead) and use distinct() or with Query Builder:
$leadIds = DB::table('level_students')->select('lead_id')->distinct()->get();
If you want to get the referenced table's column (e.g. leads table's name column) then you can use JOIN. Check Laravel's doc for more options. For example, assuming the table name for Lead is leads, then:
$leads = DB::table('level_students')->join('leads', 'level_students.lead_id', '=', 'leads.lead_id')->select('level_students.lead_id', 'leads.name')->distinct()->get();
Let me explain the scenario.
i have tables:
competitions
id title body
then
books
id name user_id
then i have a pivot table to store participants
so
participants
id competition_id user_id
Now i have set some relationships for these models.
Competition model
public function participants()
{
return $this->belongsToMany('App\User');
}
User model
public function participatedCompetitions()
{
return $this->belongsToMany('App\Competition');
}
Now i am fetching one single competition and in that same query i need to fetch a list of books of the participants of that competition.
So how can i achieve this.
Thanks.
Here is how you get all the books:
$userIds = $competition->participant()->get()->pluck('id');
// $userIds is your collection of User Ids that is participant in that compititions.
$books = Book::whereIn('user_id',$userIds)->get();
So I have 2 tables, TABLE1 and TABLE2.
They are linked throug Eloquent:
TABLE1 has many TABLE2's, and TABLE2 has one TABLE 1.
They are linked with foreign keys as such:
in TABLE2 table1_id -> links to -> TABLE1 id.
How do I retrieve the entire table data or TABLE 2, + replace table1_id with a column of table1 (let's say by booktitle for example)?
Sorry for the abstraction, but this is the best way I can explain it? :D
The easiest way is to make use of Eloquent's eager loading and fetch all records from table2 and their corresponding record in table1.
This will do the trick:
$results = Table2::with('table1')->get();
foreach ($results as $table2record) {
echo $table2record->id; //access table2 data
echo $table2record->table1->booktitle; //access table1 data
}
You need to make the relationship in the models , for example if you have a "Category" and this has many "Products" you need to put this code in your model
public function products()
{
return $this->hasMany('App\Product', 'foreign_key_you_have');
}
and when you need to retrieve all products associated to that category in your view you need to call the function of model, for example
#foreach($category->products as $cp) // with $category->products you call all products associated to your foreign_key
<h1>{{$cp->price}}</h1>
#endforeach
I need to get count of a records groupBy using with() function known as eager loading. I have two tables having one-to many relationship.
Properties:
id
name
address
Banner_Invoices:
id
property_id
start_date
end_date
Property Model has following relationship function with Banner_Invoices table:
public function bannerInvoices()
{
return $this->hasMany('BannerInvoice');
}
Now following is my query:
$properties = Property::with(array('country', 'city',
'bannerInvoices' => function($query) {
$query->where('end_date','>',date(date("Y-m-d")))
->groupBy('banner_invoices.status')
->select(DB::raw('COUNT(banner_invoices.id)')) ;
}))->get();
I am not been able to get the count of records groupBy with the status of banner Invoices. It gives me the records of banner_invoices table corresponding to a particular property.