这些是我的模型
class DateAttribute extends Eloquent{
public function xmlDocument(){
return $this->belongsTo('XMLDocument');
}
}
class XMLDocument extends Eloquent{
public function dateAttribute(){
return $this->hasOne('DateAttribute');
}
}
XMLDocument
模型具有 DateAttribute
模型之一。我可以成功地插入到两个表中。
现在我正在尝试读取特定的 xml 文档。换句话说,我正在尝试查看该 xml 文档。
我在我看来试过这个:
<td>{{$xmlDocument->dateAttribute->name}}</td>
I got this error:
SQLSTATE[42S22]: Column not found: 1054 Unknown column 'date_attribute.x_ml_document_id' in 'where clause' (SQL: select * from `date_attribute` where `date_attribute`.`x_ml_document_id` = 10 limit 1)
我不知道为什么会这样,我有很多很多关系,而且都在工作,只有这个不工作
请注意错误消息有 x_ml_document_id
x
和 ml
之间有一个下划线
,我搜索了所有代码,我根本没有那个词。
请帮忙
最佳答案
这是由您的模型命名引起的。默认情况下,Eloquent 会尝试通过读取模型名称来找出您使用的本地键和外键。如您所见,您的 DateAttribute
模型变为 date_attribute
。 CamelCase 转换为下划线。
Take note that Eloquent assumes the foreign key of the relationship based on the model name. In this case, Phone model is assumed to use a user_id foreign key. If you wish to override this convention, you may pass a second argument to the hasOne method. Furthermore, you may pass a third argument to the method to specify which local column that should be used for the association
因此,要解决您的问题,请在 hasOne
的第二个和第三个参数中定义您的外键/本地键。例如:
class XMLDocument extends Eloquent
{
// Define table name
protected $table = 'xml_document';
public function dateAttribute()
{
return $this->hasOne('DateAttribute', 'xml_document_id');
}
}
关于php - laravel 查询有一个额外的下划线符号,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24723047/