I've got 3 tables:
Car: belongsToMany Owner
Owner: belongsToMany Car
CarOwner: pivot table for Car and Owner with an additional column 'active' that indicates who is the current Owner of a Car
So a Car might have multiple or no Owners and vica versa BUT a Car has only 1 current ('active') Owner.
class Car extends Model
{
use HasFactory;
public function owners()
{
return $this->belongsToMany(Owner::class, 'car_owners');
}
public function currentOwner()
{
return $this->owners()->where('active', true)->first();
}
}
My problem is if a Car has no active Owner, Laravel throws the following exception when I want to use $car->currentOwner in a Blade template:
App\Models\Car::currentOwner must return a relationship instance, but "null" was returned. Was the "return" keyword used?
How can I handle if a Car doesn't have any active Owners?
You can create a custom attribute instead of a relation function:
public function getCurrentOwnerAttribute()
{
return $this->owners()->where('active', true)->first();
}
Related
I have three table which is explained below
User
id
email
password
specialities
id
name
active
results
id
specialitie_id
user_id
result
color
i am trying to relate results with the rest of the 2 tables, but i don't know how to do it, below is my model relation, please correct me if there's any issue, i can't fetch the data due to having wrong relation
Result Model
class Result extends Model
{
use HasFactory;
protected $guarded = [];
public function user()
{
return $this->belongsTo(User::class);
}
public function speciality()
{
return $this->belongsTo(Speciality::class);
}
}
User Model
class User extends Authenticatable implements MustVerifyEmail
{
public function result()
{
return $this->hasMany(Result::class);
}
}
i am trying to expect a correct result of my relation database tables in laravel
Since the results table is Intermediate Table Columns.use laravel belongsToMany method so no need to create results model.Treat results table as pivot table.
In User Model add relation like below
public function specialities()
{
return $this->belongsToMany(Speciality::class,'results')->withPivot('result','color');
}
Also read here Many To Many Relationships
I want to have two tables one for Employees and one for Companies, both Employees & Companies should be registered within the site, thus they should have records in the users table provided with Laravel. How should I structure the relationships between the models, should I go for polymorphic relationships or use one to one?
The answer is to add two columns to the "users" table: userable_id and userable_type. userable_id will be used to store the id of the row for the entity (Employee or Company), and the userable_type will hold the class path for the Eloquent model.
in create_users_table migration file add these two lines:
// ...
$table->integer('userable_id')->unsigned();
$table->string('userable_type');
// ...
in User.php model:
class User extends Model {
// Add this declaration.
public function userable()
{
return $this->morphTo();
}
}
in your Company.php model:
class Company extends Model
{
// Add this method.
public function user()
{
return $this->morphMany(User::class, 'userable');
}
}
in the Employee.php model do the same as above:
class Employee extends Model
{
// Add this method.
public function user()
{
return $this->morphMany(User::class, 'userable');
}
}
Now you should be able to access the user by running:
App\Company::all()->get(1)->user;
// or
App\Employee::all()->get(1)->user;
And access the entity with this one-liner:
App\User::all()->get(1)->userable;
I have three table which I wanna associate. Shipment_methods, Ship_companies and Payment_methods.
Relations:
Shipment_methods <- pivot1 -> Ship_companies
pivot1 <- pivot2 -> Payment_methods
Well, what I wanna do is e.g. ShipmentMethod_A is attached to ShipCompany_B and for this record (from pivot1) I wanna attach record from Payment_method table through pivot2 table.
ShipmentMethod Model:
public function ship_companies()
{
return $this->belongsToMany(ShipCompany::class, 'shipment_methods_ship_companies', 'shipment_method_id', 'ship_company_id')->withPivot('price_kc', 'price_ha');
}
ShipCompany Model:
public function shipment_methods()
{
return $this->belongsToMany(ShipCompany::class, 'shipment_methods_ship_companies', 'ship_company_id', 'shipment_method_id');
}
What I need to do is I wanna retrieve all Payments for ShipCompany of specific ShipmentMethod like
ShipmentMethods->ship_companies->pivot->payments_methods
Thanx.
I think best way is for you to have a Model that extend Pivoted class for you pivot1. the pivot1 should have id column to use in pivot2. so the code should be like this,
ShipmentMethod Model:
public function ship_companies()
{
return $this->belongsToMany(ShipCompany::class, 'shipment_methods_ship_companies', 'shipment_method_id', 'ship_company_id')->using('App\pivot1')->withPivot('id','price_kc', 'price_ha');
}
note that I have put id in withPrivot and chain using() method
your pivot1 model should be like this,
pivot1 Model:
use Illuminate\Database\Eloquent\Relations\Pivot;
class pivot1 extends Pivot
{
public function Payment_methods()
{
return $this->belongsToMany(Payment_methods::class, 'pivot2_table_name', 'pivot1_id', 'payment_method_id');
}
}
and at the end you can do like this to save to pivot2
ShipmentMethods->ship_companies->pivot->payments_methods()->sync([payment_method_ids])
as all pivot relationship return a collection of array note that you need to loop ShipmentMethods->ship_companies relationship to get to pivot relationship.
Hope this helps!
I am not much familiar with eloquent orm in laravel
I have 3 tables they are
-- leads
|
Lead_appointments
and users table
since lead_appointments belongs to leads references id on leads by lead_id
the leads_appointments has a column called created_by with user's id in it
I am trying to query user's name and email along with the result as another column when query using eloquent
Lead Model
class Leads extends Model
{
public function appointments()
{
return $this->hasMany('App\Models\LeadsAppointments', 'lead_id');
}
}
My eloquent query in controller
return $this->lead->with('appointments')->find($id);
the result is like this
In under appointments i also want user email and name along with created by in it
But I couldn't figure it out
Add a relation to LeadAppointment model like this:
class LeadAppointment extends Model
{
public function users()
{
return $this->belongsTo('App\Models\User', 'created_by');
}
}
and change leads model like this:
class Leads extends Model
{
public function appointments()
{
return $this->hasMany('App\Models\LeadsAppointments', 'lead_id')->with('users');
}
}
Have three entities:
Project
Employee
Employment
Problem description: Employee can work on many projects and for each he has one employment. I want to have access to all projects and your referred employments of a certain employee.
I'm not sure but the relationship must look like a ternary:
The physical table is not defined yet. So, be free to design (most basic) them.
And my question:
How i can build using Laravel Eloquent Relationships?
Basically your four tables will be something like:
employee
id
...your fields
project
id
...your fields
employments
id
...your fields
employee_project
employee_id
project_id
employment_id
You can split the problem in 2 by 2 relations:
class Employee extends Model{
public function projects(){
return $this->belongsToMany("Project")
}
// Second relation is Optional in this case
public function employments(){
return $this->belongsToMany("Employment", 'employee_project')
}
}
A Project model
class Project extends Model{
public function employees(){
return $this->belongsToMany("Employee")
}
// Second relation is Optional in this case
public function employments(){
return $this->belongsToMany("Employment",'employee_project')
}
}
A Employment model
class Employment extends Model{
public function employees(){
return $this->belongsToMany("Employee")
}
public function projects(){
return $this->belongsToMany("Project")
}
}
At this point in your controller you can manage your relation, for example if you want to add to $employee, the project with id 1 with the employment with id 2 you can simply
$employee->projects()->attach([1 => ['employment_id' => '2']]);
I hope this answer to your question.
If you need timestamps in your pivot table, add ->withTimesetamps() to your relationships.
Employee has Employment
Employment has Project