简体   繁体   中英

Laravel Eloquent Relationship

I have a sales model defined and when I call Quote::find('1'); it is not returning my sales object. Have I done something wrong with my relationship? Here is the table structure:

Quote: id, companyName, stage, saleId

Sale: id, name, phoneNumber

Class Quote extends Eloquent
{

    protected $with = ['sale'];

    public function sale()
    {
        return $this->hasOne('Sale', 'id');
    }
}

In my Sale model I have defined:

public function quote()
{
    return $this->belongsTo('Quote');
}

I figured it out. Had my relationship backwards.

Class Quote extends Eloquent
{

    protected $with = ['sale'];

    public function sale()
    {
        return $this->belongsTo('Sale', 'saleId');
    }
}

To understand it better I think you can say that in a belongs_to relationship, the foreign key resides in the table of the model you are trying to create the relationship from. So the above function could be read like "saleID belongsTo Sale model".

The foreign key resides in the other model's table when using has_one.

Try this:

$quote = Quote::with('sale')->find(1);

You should be able to then go something like this $quote->sale->name

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM