php - laravel 查询有一个额外的下划线符号

标签 php mysql sql laravel laravel-4

这些是我的模型

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 xml 之间有一个下划线,我搜索了所有代码,我根本没有那个词。

请帮忙

最佳答案

这是由您的模型命名引起的。默认情况下,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/

相关文章:

php - 如何从laravel中的中间表中获取数据?

PHP/HTML : Creating an element using php, 点击一个按钮

php - 改进显示 max_user_connections 的站点

php - 将变量 javascript 传递到 php

mysql - 仅当父值不为 NULL 时才根据父 ID 更新单元格

java - 获取要绘制的数据样本

sql - 如果不存在则插入两个表的总和

php - 在单个表中使用 if 进行计数并在两个单独的列中显示结果 - mysql

MySql 服务器未启动

SQL 连接只允许每个表中有一个匹配项