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