【发布时间】: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