Laravel 5雄辩的关系返回空或null,但代码似乎没有问题


Laravel 5 eloquent relationship returns empty or null but the code seems ok

我做了一些搜索,但仍然不能解决这个问题,我正在编写一个小图书馆网站学习,我不能得到的关系工作。(libro = book, author = author, genere = genre)

在我的修补程序中命令

$libro->autore

返回null或空,即使我将其作为方法调用并使用toArray

这是我的代码:

<<p> Libro模型/strong>
namespace App;

数据库使用说明' '雄辩'模型;

class Libro extends Model
{
    protected $table = 'libri';
    protected $fillable = ['titolo', 'id_autore', 'pubblicazione', 'trama', 'voto', 'image_url', 'id_genere'];
    public function genere() {
        return $this->belongsTo('App'Genere');
    }
    public function autore() {
        return $this->belongsTo('App'Autore');
    }
}
<<p> Autore模型/strong>
namespace App;
use Illuminate'Database'Eloquent'Model;
class Autore extends Model
{
    protected $table = 'autori';
    protected $fillable = ['nome', 'cognome', 'nascita', 'paese'];
    public function libri() {
        return $this->hasMany('App'Libro');
    }
    public function getFullNameAttribute()
    {
        return $this->nome . " " . $this->cognome;
    }
}

my migration

$table->foreign('id_autore')->references('id')->on('autori');
$table->foreign('id_genere')->references('id')->on('generi');

我在mysql数据库中添加了外键,检查了phpmyadmin,但仍然不起作用,我做错了什么?

**添加更多修补响应尝试**如果我尝试:

>>> App'Autore::find(2)->libri()->get()

:

Illuminate'Database'QueryException with message 'SQLSTATE[42S22]: Column not found: 1054 Unknown column 'libri.autore_id' in 'where clause' (SQL: select * from `libri` where `libri`.`autore_id` = 2 and `libri`.`autore_id` is not null)'

如果我尝试:

$libro-autore()

我得到:

BadMethodCallException with message 'Call to undefined method Illuminate'Database'Query'Builder::autore()'

而不是
$libro->autore

还是

null

关系中列的命名约定不正确(反向)。约定为${related_table}_id

要解决这个问题,请更改您的迁移。否则,如果你不想调整你的迁移,那么在你的Autore模型中指定外键列作为hasMany关系的第二个参数。

public function libri() {
    return $this->hasMany('App'Libro', 'id_autore')
}

确保对Libro模型做相反的操作。