where pivot laravel code example
Example 1: has many through laravel
class Country extends Model
{
public function posts()
{
return $this->hasManyThrough(
'App\Post',
'App\User',
'country_id',
'user_id',
'id',
'id'
);
}
}
when
countries
id - integer
name - string
users
id - integer
country_id - integer
name - string
posts
id - integer
user_id - integer
title - string
Example 2: laravel has one through
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class Mechanic extends Model
{
public function carOwner()
{
return $this->hasOneThrough('App\Owner', 'App\Car');
}
}
Example 3: laravel detach
$user->roles()->detach($roleId);
$user->roles()->detach();
Example 4: laravel belongs to
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Model;
class Phone extends Model
{
public function user()
{
return $this->belongsTo('App\Models\User');
}
}
Example 5: laravel pivot table model
public function customer(){
return $this->belongsToMany('customer')->withPivot(
'start_date',
'stop_date',
'rem_date',
'due_date',
'status'
);
}
public function services(){
return $this->belongsToMany('Service')->withPivot(
'start_date',
'stop_date',
'rem_date',
'due_date',
'status'
);
}
public function staff(){
return $this->belongsToMany('Staff');
}
public function custservs(){
return $this->belongsToMany('Custserv');
}
Schema::create('customer_service_user', function(Blueprint $table)
{
$table->increments('id');
$table->integer('customer_service_id')->unsigned()->index();
$table->foreign('customer_service_id')->references('id')->on('customer_service')->onDelete('cascade');
$table->integer('staff_id')->unsigned()->index();
$table->foreign('staff_id')->references('id')->on('staff')->onDelete('cascade');
$table->timestamps();
});