I'm getting problems calling relationships in laravel, I have 4 tables: users, tickets, stores, statuses. and I have a @OneToMany relationship in Users to Tickets (1 user have many tickets). the other relationships are @OneToOne (1 ticket have 1 store and status).
Now, I have 6 tickets in my table and 4 users, I can print the relationship to the 4 first tickets, but when I want to call the ticket 5 or 6, the relationship dissapears. The same thing with store and status, I can print the relationship while the id of the ticket is not greater than the number of items I have in my table.
these are my models:
User Model:
class User extends Authenticatable
{
use Notifiable, HasRoles;
protected $fillable = [
'id','name', 'email', 'password',
];
protected $hidden = [
'password', 'remember_token',
];
public function tickets()
{
return $this->hasMany(Ticket::class, 'usuario_id');
}
}
Ticket Model:
class Ticket extends Model
{
protected $fillable = [
'comentarios', 'falla', 'modelo', 'no_serie', 'monto',
'usuario_id', 'status_id', 'store_id'
];
public function user()
{
return $this->belongsTo(User::class, 'id');
}
public function store()
{
return $this->hasOne(Store::class, 'id');
}
public function status()
{
return $this->hasOne(Status::class, 'id');
}
}
Store Model:
class Store extends Model
{
protected $table = "stores";
protected $primaryKey = 'id';
public $timestamps = false;
protected $fillable = [
'sucursal', 'dirección'
];
public function ticket()
{
return $this->belongsTo(Ticket::class, 'store_id');
}
}
Status Model:
class Status extends Model
{
public $timestamps = false;
protected $fillable = [
'status'
];
public function ticket()
{
return $this->belongsTo(Ticket::class, 'status_id');
}
}
Controller:
$tickets = Ticket::all();
return view('Admin.index', compact('tickets'));
View
@foreach($tickets as $ticket)
{{ $ticket->user }}
@endforeach
result:
-{"id":1,"name":"Eduardo Q","email":"[email protected]"}
-{"id":1,"name":"LareOrt","email":"eduardo.grquinonez1@gmail.com"}
-{"id":1,"name":"Octavio M","email":"eduardo.grquinonez2@gmail.com"}
-{"id":1,"name":"Ramon R","email":"eduardo.grquinonez3@gmail.com"}
In the view, I'm calling all the tickets ($tickets), and for each ticket (6) I print the relationship (user function). But in the result just print first 4 relationships, (the number of my users), if I add 1 user, the relationship in the 5th ticket appears. The Same problem with the other tables (store and status).
Note: The 5 and 6 tickets have relation with user_id 3, whereby they would print the relationship with the user 3.