Two foreign keys pointing to the same table / model - laravel

I have two models:
TRUCK
DRIVER
TRUCK has two fields which are FKs. Driver (FK) and Driver2 (FK).
When I try to get the truck with driver and driver2, I get two same records.
$truck = $this->instance->truck()->where('id', $id)
->with(['driver', 'driver2',])
->firstOrFail();
My Truck Model:
class Truck extends Model
{
use SoftDeletes;
protected $table = 'trucks';
protected $guarded = ['id'];
protected $dates = ['deleted_at'];
public function driver()
{
return $this->hasOne('App\Models\Driver');
}
public function driver2()
{
return $this->hasOne('App\Models\Driver');
}
My Driver Model:
class Driver extends Model
{
use SoftDeletes;
protected $table = 'drivers';
protected $guarded = ['id'];
protected $dates = ['deleted_at'];
public function truck()
{
return $this->belongsTo('App\Models\Truck');
}
I am still new to laravel and something I get stuck. Should I create another model instead maybe?

By default laravel will use default foreign key,
Eloquent assumes the foreign key of the relationship based on the
model name #Further reading
So both relation are pointing to the same FK, So you need to specify the foreign key as below
return $this->hasOne('App\Models\Driver', 'Driver');
return $this->hasOne('App\Models\Driver', 'Driver2');
Full code
class Truck extends Model
{
use SoftDeletes;
protected $table = 'trucks';
protected $guarded = ['id'];
protected $dates = ['deleted_at'];
public function driver()
{
return $this->hasOne('App\Models\Driver', 'Driver');
}
public function driver2()
{
return $this->hasOne('App\Models\Driver', 'Driver2');
}

Related

One to Many Relationship with Pivot Table and fetch related data using the with method

In Laravel 5.5 application, I have a model called Meeting and a model called Room.
Both models have a many-to-many relationship through a pivot table called MeetingSchedule.
The MeetingSchedule table has a column called schedule_by which is a foreign key to the user_id column in the User table.
I want to get the email address of the user who scheduled the meeting, when I fetch the meeting details with schedules() function of Meeting model.
I have tried the following code but it does not work:
class Meeting extends Model {
protected $table = 'Meetings';
protected $primaryKey = 'meeting_id';
protected $fillable = ['topic', 'description', 'participants_count'];
public function schedules() {
return $this->belongsToMany('App\Room', 'MeetingSchedule', 'meeting_id', 'room_id')
->using('App\MeetingSchedule')
->withPivot('schedule_id', 'start_time', 'end_time', 'scheduled_by')
->whereNull('MeetingSchedule.deleted_at')
->withTimestamps();
}
}
class Room extends Model {
protected $table = 'Rooms';
protected $primaryKey = 'room_id';
protected $fillable = ['name', 'location', 'capacity'];
public function schedules() {
return $this->belongsToMany('App\Meeting', 'MeetingSchedule', 'room_id', 'meeting_id')
->using('App\MeetingSchedule')
->withPivot('schedule_id', 'start_time', 'end_time', 'scheduled_by')
->whereNull('MeetingSchedule.deleted_at')
->withTimestamps();
}
}
class MeetingSchedule extends Pivot {
protected $table = 'MeetingSchedule';
protected $primaryKey = 'schedule_id';
public function scheduledBy() {
return $this->belongsTo('App\User', 'scheduled_by', 'user_id');
}
}
class User extends Authenticatable {
protected $table = 'User';
protected $primaryKey = 'user_id';
protected $fillable = ['username', 'email'];
public function meetingScheduledBy()
{
return $this->hasMany('App\MeetingSchedule', 'scheduled_by', 'user_id');
}
}
function getMeetingWithRelatedData($meetingId) {
return Meeting::where('meeting_id', $meetingId)
->with(['schedules'])
->first();
}

nested eager loading or hasManyThrough in laravel is not working

i want to get nama from Supplier table using PembelianDetail table through Pembelian table using this code :
$detail = PembelianDetail::with('supplier')->whereBetween('tanggal',[$awal, $akhir])->where('id_produk', $produk->id_produk)->get();
with this model :
class Supplier extends Model
{
use HasFactory;
protected $table = 'supplier';
protected $primaryKey = 'id_supplier';
protected $guarded = [];
public function pembelian()
{
return $this->hasMany(Pembelian::class, 'id_pembelian', 'id_pembelian');
}
public function pembelian_detail(){
return $this->hasManyThrough(PembelianDetail::class, Pembelian::class );
}
}
class Pembelian extends Model
{
use HasFactory;
protected $table = 'pembelian';
protected $primaryKey = 'id_pembelian';
protected $guarded = [];
public function supplier()
{
return $this->belongsTo(Supplier::class, 'id_supplier', 'id_supplier');
}
public function pembelian_detail()
{
return $this->hasMany(PembelianDetail::class, 'id_pembelian_detail', 'id_pembelian_detail');
}
}
class PembelianDetail extends Model
{
use HasFactory;
protected $table = 'pembelian_detail';
protected $primaryKey = 'id_pembelian_detail';
protected $guarded = [];
public function pembelian()
{
return $this->belongsTo(PembelianDetail::class, 'id_pembelian_detail', 'id_pembelian_detail');
}
}
and keep getting this error :
Call to undefined relationship [supplier] on model [App\Models\PembelianDetail].
with the same way i dont understand how that works in this tutorial https://www.youtube.com/watch?v=5s-_SnVl-1g and i just followed the same steps but keep getting that error.
i also tried nested eager loading according laravel documentation by using :
$detail = PembelianDetail::with('pembelian.supplier')->whereBetween('tanggal',[$awal, $akhir])->where('id_produk', $produk->id_produk)->get();
but get the same error and other queries works fine
Am i missing something here?

How to Bind A model data to all of child Models in Laravel

I have a model for custom fields,I want to bind the configuration detail for all model extended by Base model!
my CoctomFormBulder Model
class CustomFormBuilder extends \Eloquent
{
protected $fillable = [];
protected $table = 'custom_fields_configure';
}
Here is My base model and what I have try up to now.
class BaseModel extends \Eloquent {
protected $guarded = array('q');
protected $table = 'custom_fields_configure';
protected $appends = ['configure'];
public function getConfigerAttribute() {
if (isset($this->attributes['configure'])) {
//return URL::asset($this->attributes['image']);
return $this->attributes['configure'];
}
return '';
}
public function setConfigerAttribute($configure) {
$this->attributes['configure'] = $configure;
}
}
How can Bind Data from CustomFormBuilder to all of my models in the app
Just let the models that need that logic extends the 'CustomFormBuilder' class

laravel muti lavel association

I have 3 tables and these table are not according laravel
job_post Table
job_post_id
name
job_functional_area Table (has many with job_post table and belongsTo with functional_area)
job_functional_area_id
job_post_id
functional_area_id
functional_area
functional_area_id
name
now I want to fetch job_post functional area
Relation like this job_post > job_functional_area > functional_area
In cakephp we use contain in laravel i don't have an idea.
I have try Has Many Through but it will not work in this condition. Please help me
Models
class JobPost extends Model
{
protected $table = 'job_post';
protected $primaryKey = 'job_post_id';
}
class JobFunctionalArea extends Model {
protected $table = 'job_functional_area';
protected $primaryKey = 'job_functional_area_id';
}
class FunctionalArea extends Model {
protected $table = 'functional_area';
protected $primaryKey = 'functional_area_id';
}
Your models should look something like this.
class JobPost extends Model {
protected $table = 'job_post';
protected $primaryKey = 'job_post_id';
public function jobFunctionalAreas() {
return $this->belongsToMany('App\JobFunctionalArea');
}
}
class JobFunctionalArea extends Model {
protected $table = 'job_functional_area';
protected $primaryKey = 'job_functional_area_id';
public function jobPosts() {
return $this->hasMany('App\JobPost');
}
public function functionalArea() {
return $this->belongsTo('App\FunctionalArea');
}
}
class FunctionalArea extends Model {
protected $table = 'functional_area';
protected $primaryKey = 'functional_area_id';
public function jobFunctionalAreas() {
return $this->hasMany('App\JobFunctionalArea');
}
}
Also in the relations you can add your own custom $primaryKey.

Eloquent firstOrCreate documentation or usage

I'm attempting to seek a table to see if a column named "name" exists if so return the value and if not create that row with a null value i saw firstOrCreate but i cannot figure out how to use it for the life of me.
This is what i currently have, can someone lend a hand?
class Settings extends Eloquent
{
protected $table = 'settings';
protected $primaryKey = 'name';
public static function get($settingName)
{
return self::firstOrCreate(array('name' => $settingName));
// return self::select(array('value'))->where('name', '=', $settingName)->first()->value;
}
}
The create() method does mass assignment and this is a big security issue, so Laravel has a protection against it. Internally it has guarded = ['*'], so all your columns will be protected against mass assignment. You have some options:
Set the fillable columns of your model:
class User extends Eloquent {
protected $fillable = array('first_name', 'last_name', 'email');
}
Or set only the ones you want to keep guarded:
class User extends Eloquent {
protected $guarded = array('password');
}
You may, at your own risk also do:
class User extends Eloquent {
protected $guarded = array();
}
And everything will be unguarded.
Take a look a the docs: http://laravel.com/docs/eloquent#mass-assignment
You also could use your Facade to call it:
class Settings extends Eloquent
{
protected $table = 'settings';
protected $primaryKey = 'name';
public static function get($settingName)
{
return Settings::firstOrCreate(array('name' => $settingName));
}
}

Resources