I'm doing my first project with laravel 5.5 aç and now I'm establishing models and relationships
My project consists of a social network of video games.
The two models that I want to relate are the following, it would be a many-to-many relationship:
the genre of the game:
class Genero extends Model
{
protected $primaryKey = "cod";
public $incrementing = true;
protected $keyType = "int";
protected $table = "generos";
protected $fillable = ["cod","nombre"];
//public $timestamps = false;
public function juegos(){
return $this->belongsToMany('App\Juego',"juegosGeneros","codGenero","codJuego");
}
}
And the Game
class Juego extends Model
{
protected $primaryKey = "codJuego";
public $incrementing = false;
protected $keyType = "int";
protected $table = "juegos";
protected $fillable = ["cod", "nombre"];
//public $timestamps = false;
public function generos(){
return $this->belongsToMany('App\Genero',"juegosGeneros","codJuego","codGenero");
}
}
My db tables are that:
CREATE TABLE juegos(
cod INT AUTO_INCREMENT,
nombre VARCHAR(50),
PRIMARY KEY (cod)
);
CREATE TABLE generos(
cod INT AUTO_INCREMENT,
nombre VARCHAR(50),
PRIMARY KEY (cod)
);
CREATE TABLE juegosGeneros(
codJuego INT,
codGenero INT
);
My problem: I have inserted data in the tables and when retrieving them
<?php
$juego = \App\Juego::where("cod","1")->first();
dd($juego->generos);
?>
they returned me an empty array
Collection {#188 ▼
#items: []
}
Observing the queries made to the database laravel do this:
select `generos`.*, `juegosGeneros`.`codJuego` as `pivot_codJuego`, `juegosGeneros`.`codGenero` as `pivot_codGenero`
from `generos`
inner join `juegosGeneros`
on `generos`.`cod` = `juegosGeneros`.`codGenero` where `juegosGeneros`.`codJuego` is null
Idont know the reason of this condition, and I think that is the problem
where `juegosGeneros`.`codJuego` is null
I really appreciate your help
You set the wrong primary key:
class Juego extends Model
{
protected $primaryKey = "cod";
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.