I need some fields (SCORE, HEALTH) in many-to-many relation.
Models
Channel => title
Company => id
Tables
channels => id, title
companies => id
company_channel => channel_id, company_id, SCORE, HEALTH
The question is: do I have to set withPivot fields on both models?
// channel model
public function companies() { return $this->belongsToMany('\App\Company')->withPivot(['score', 'health']); }
// company model
public function channels() { return $this->belongsToMany('\App\Channel')->withPivot(['score', 'health']); }
Related
I have a users table, a products table, and and an assets table. A user can have many assets, as can a product, meaning both Users, and Products have a 1:n relationship with assets. In Laravel how would show this relationship in Eloquent, is this a Polymorphic relationship, with the struct of the assets table columns being something like,
ID, type, file_path, ownable_id, ownable_type
I think your assets table columns should be
id, type, file_path, assetable_id, assetable_type
Add this relation to your user and product model
public function assets()
{
return $this->morphMany(Asset::class, 'assetable');
}
Next, add this relation to your asset model
public function assetable()
{
return $this->morphTo();
}
relation of user model
public function assets()
{
return $this->morphMany(Asset::class, 'assetable');
}
relation of asset model
public function assetable()
{
return $this->morphTo();
}
For example i have 4 tables:
buildings
id, title, ...
rooms
id, building_id, title, ...
companies
id, title, ...
companies_to_buildings
company_id, building_id
and i want to get companies from the room model.
From building model i can do something like
class Building extends Model
{
public function companies(){
return $this->belongsToMany('App\Company', 'company_building');
}
}
or
class Building extends Model
{
public function companies(){
return $this->belongsToMany('App\Company', 'company_building', 'building_id', 'company_id');
}
}
but if i do this in room model, it would not work. it will try to find rows in companies_to_buildings table where companies_to_buildings.building_id=room.id. how can i get companies from the room model?
You can make use of hasManyThrough
Example:
public function series()
{
return $this->hasManyThrough('Series', 'Product');
}
Requested tables are listed below:
**User Table**
id, name
1, vehicle person name
2, renter person name
**Vehicle Table**
id, user_id, vehicle_name
1, 1, My car
**Booking Table**
id, renter_id, vehicle_id
1, 2, 1
User Model
public function renter() {
return $this->hasMany(Booking::class, 'renter_id');
}
public function vehicleBook() {
return $this->hasManyThrough(Booking::class, Vehicle::class);
}
Booking Model
public function user() {
return $this->belongsTo(User::class, 'renter_id');
}
Vehicle Model
public function user() {
return $this->belongsTo(User::class);
}
My Controller
$renters = Auth::user()->renter()->get();
$owners = Auth::user()->vehicleBook()->get();
// In Loop
$renter->user->name; // renter person name
$owner->user->name; // vehicle person name
Result
On base of booking Table i want to get renter person and vehicle person name using Laravel 5 ORM.
I have done that using two calls but i want to know if there is any way to get result using one call ?
You could do something like this. It will reduce the number of lines, but will increase the number of queries.
$user = User::find(Auth::user()->id)->with('renters')->with('vehicleBooks')->first();
I have an object Tournament and 2 relations:
A tournament belongs to a user ( the admin who created it)
A tournament hasMany users ( Competitors )
I can distinct one from other with his role ( Admin, competitor )
Can I do that, or should I get conflicted???
If not, how should I do it???
You can do this - you just need to define 2 relations for your Tournament object, e.g.:
class Tournament extends Model {
public function admin() {
return $this->belongsTo(User::class, 'admin_id');
}
public function competitors() {
return $this->belongsToMany(User::class);
}
}
Your tournament-admin relation key will now be stored in admin_id field of your tournaments table, while tournament-competitor mapping will be stored in user_tournament table - make sure you have one.
You can read more about operating on many-to-many relationships here: http://laravel.com/docs/5.1/eloquent-relationships#many-to-many
Suppose I have the next 4 related tables:
countries
---------
(PK) id
country_name
...
cities
------
(PK) id
(FK) country_id
city_name
...
districts
---------
(PK) id
(FK) city_id
district_name
...
areas
-----
(PK) id
(FK) district_id
area_name
...
And suppose I want to get all countries with cities that belong to each country, and districts that belong to each city, and areas that belong to each district, and I want to get only specific columns from each table. How can I do this with eager loading in Laravel?
First you need to set relationships between these tables in their models like this:
// in models/Country.php file (countries model)
/**
* City relationship
*/
public function cities()
{
return $this->hasMany('City');
}
// in models/City.php file (cities model)
/**
* Country relationship
*/
public function country()
{
return $this->belongsTo('Country');
}
/**
* District relationship
*/
public function districts()
{
return $this->hasMany('District');
}
// in models/District.php file (districts model)
/**
* City relationship
*/
public function city()
{
return $this->belongsTo('City');
}
/**
* Area relationship
*/
public function areas()
{
return $this->hasMany('Area');
}
// in models/Area.php file (areas model)
/**
* District relationship
*/
public function district()
{
return $this->belongsTo('District');
}
And finally you can use the next code in any controller to get the required data:
$countries = Country::with([
"cities" => function($q1) {
$q1->with([
"districts" => function($q2) {
$q2->with([
"areas" => function($q3) {
$q3->select(["id", "district_id", "area_name"]) // columns that you want to get from areas table
->where("id", ">", 1)
->orderBy("id", "asc");
}
])
// You must always select the foreign key or the primary key of the relation
// otherwise Laravel won't be able to link the models together
->select(["id", "city_id", "district_name"]) // columns that you want to get from districts table
->where("id", ">", 5)
->orderBy("id", "asc");
}
])
// You must always select the foreign key or the primary key of the relation
// otherwise Laravel won't be able to link the models together
->select(["id", "country_id", "city_name"]) // columns that you want to get from cities table
->where("id", ">", 10)
->orderBy("id", "asc");
},
])
->select(["id", "country_name"]) // columns that you want to get from countries table
->where("id", ">", 15) // in case you have a condition
->orderBy("id", "asc") // in case you want to order results
->get();
return $countries;
Note that you must always select the foreign key or the primary key of the relation, otherwise Laravel won't be able to link the models together.