【问题标题】:Laravel 5 eloquent relationship returns empty or null but the code seems okLaravel 5 雄辩的关系返回空或 null 但代码似乎没问题
【发布时间】:2016-09-20 15:35:39
【问题描述】:

我进行了一些搜索,但仍然无法解决这个问题,我正在编写一个小型图书馆网站以供学习,但我无法建立关系。 (libro = 书,autore = 作者,genere = 流派)

在我的修补程序中,命令

$libro->autore

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

这是我的代码:

Libro 模型

namespace App;

使用 Illuminate\Database\Eloquent\Model;

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');
    }
}

Autore 模型

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;
    }
}

我迁移中的关系

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

我在 mysql db 中添加了外键,在 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

【问题讨论】:

  • 你能添加你的控制器逻辑吗?
  • 我正在使用 tinker 来显示内容,我不明白粘贴只为视图做事的控制器有什么意义
  • 你试过$libro->autore()
  • 是的,我还在主帖中添加了更多的修补回复,请仔细阅读

标签: php database laravel eloquent relation


【解决方案1】:

您对关系中列的命名约定不正确(向后)。约定是${related_table}_id。

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

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

并确保对 Libro 模型执行相反的操作。

【讨论】:

  • 所以外键没有自动设置?我认为 ->foreign 和 ->references 的组合会设置
  • 数据库模式和模型模式互不了解。你必须明确告诉他们如何沟通。
  • 另外很抱歉,tinker 仍然返回空数组,并且 $libro->autore 仍然为空
  • 对不起,我的错,我不得不将它也添加到 belongsTo,非常感谢!那是我的问题,很抱歉没有看到错误的 sql 查询。
  • @K3nzie 对不起,不得不走开。我应该澄清你也需要做相反的事情。我很抱歉。
猜你喜欢
  • 2015-12-17
  • 1970-01-01
  • 2018-06-19
  • 2018-04-11
  • 2015-04-28
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-03-17
相关资源
最近更新 更多