Ad

Eloquent One To Many Issue

- 1 answer

i have a question related to the title. so i have this models (i have more code and models behind if u need tell me)

Cliente Model

protected $table = 'cliente';
protected $primaryKey = 'id_cliente';
public $timestamps = false;

public function seguroCarro()
{
    return $this->hasMany('App\SeguroCarro', 'id_seguro_carro');
}

SeguroCarro Model

protected $table = 'seguro_carro';
protected $primaryKey = 'id_seguro_carro';
public $timestamps = false;

public function cliente()
{
    return $this->belongsTo('App\Cliente', 'id_cliente');
}

Question:

This Cliente::find(1)->seguroCarro get the seguro_carro with id 1 and not with id_cliente 1 but this SeguroCarro::all()->where('id_cliente',Auth::user()->cliente->id_cliente) get the 3 rows seguro_carro i need

i dont get why this happen but i want understand why

Atencion: this Cliente::find(1)->seguroCarro is a abreviation for you guys for my code Auth::user()->cliente->seguroCarro [my Auth::user()->cliente have the id 1]

img of rows on seguro_carro table

Thank you for the time guys

Ad

Answer

The relationship on your App\Cliente model is specifying the wrong key. The second parameter to the hasOne/hasMany relationship is the name of the foreign key field on the related object. In this case, the foreign key on the related object (App\SeguroCarro) is id_cliente, not id_seguro_carro.

Your current relationship will get the seguro_carro records where seguro_carro.id_seguro_carro = cliente.id_cliente, which is not what you want.

The relationship should be changed to:

public function seguroCarro()
{
    return $this->hasMany('App\SeguroCarro', 'id_cliente');
}

This will get the seguro_carro records where seguro_carro.id_cliente = cliente.id_cliente, which is what you want.

The belongsTo relationship on your App\SeguroCarro is correct.

Ad
source: stackoverflow.com
Ad