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.

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

报告相同问题?

悬赏问题

  • ¥20 sub地址DHCP问题
  • ¥15 delta降尺度计算的一些细节,有偿
  • ¥15 Arduino红外遥控代码有问题
  • ¥15 数值计算离散正交多项式
  • ¥30 数值计算均差系数编程
  • ¥15 redis-full-check比较 两个集群的数据出错
  • ¥15 Matlab编程问题
  • ¥15 训练的多模态特征融合模型准确度很低怎么办
  • ¥15 kylin启动报错log4j类冲突
  • ¥15 超声波模块测距控制点灯,灯的闪烁很不稳定,经过调试发现测的距离偏大