dousu5608 2016-09-20 15:35
浏览 62
已采纳

Laravel 5 eloquent关系返回空或null但代码似乎没问题

I did some searching but still I can't solve this, I'm coding a little library site for learning and I can't get relationships to work. (libro = book, autore = author, genere = genre)

In my tinker the command

$libro->autore

returns null or empty, even if I call it as a method and use toArray

this is my code :

Libro model

namespace App;

use 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 Model

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

The relation in my migration

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

I added the foreign keys in the mysql db, checked that on phpmyadmin, but still, it doesn't work, what am I doing wrong?

**adding more tinker responses to try outs ** If I try:

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

I 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)'

If I try :

$libro-autore()

I get :

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

instead

$libro->autore

remains

null
  • 写回答

1条回答 默认 最新

  • dongwei1954 2016-09-20 16:15
    关注

    Your naming convention on the columns in your relation are incorrect (backwards). The convention is ${related_table}_id.

    To solve this, alter your migration. Othwise, if you don't want to just adjust your migration, then specify the foreign key column in your Autore model as the 2nd argument to your hasMany relationship.

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

    And make sure to do the inverse for the Libro model.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 乌班图ip地址配置及远程SSH
  • ¥15 怎么让点阵屏显示静态爱心,用keiluVision5写出让点阵屏显示静态爱心的代码,越快越好
  • ¥15 PSPICE制作一个加法器
  • ¥15 javaweb项目无法正常跳转
  • ¥15 VMBox虚拟机无法访问
  • ¥15 skd显示找不到头文件
  • ¥15 机器视觉中图片中长度与真实长度的关系
  • ¥15 fastreport table 怎么只让每页的最下面和最顶部有横线
  • ¥15 java 的protected权限 ,问题在注释里
  • ¥15 这个是哪里有问题啊?