[英]Laravel Eloquent Relationship
I have a sales model defined and when I call Quote::find('1');
我定义了一个销售模型,当我调用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 Quote:id,companyName,stage,saleId
Sale: id, name, phoneNumber 销售:ID,姓名,电话号码
Class Quote extends Eloquent
{
protected $with = ['sale'];
public function sale()
{
return $this->hasOne('Sale', 'id');
}
}
In my Sale
model I have defined: 在我的Sale
模型中,我定义了:
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. 为了更好地理解它,我想您可以说,在一个belongs_to关系中,外键位于您试图从中创建关系的模型的表中。 So the above function could be read like "saleID belongsTo Sale model". 因此,上面的函数可以像“ saleID归属于销售模型”那样阅读。
The foreign key resides in the other model's table when using has_one. 使用has_one时,外键位于其他模型的表中。
Try this: 尝试这个:
$quote = Quote::with('sale')->find(1);
You should be able to then go something like this $quote->sale->name
然后,您应该可以像这样$quote->sale->name
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.