mahdi pishguy
mahdi pishguy

Reputation: 1034

Laravel simple relation between models return null

In my database I have users and tickets table. Now I want to create simple relation between theme, in phpmyadmin relation created between tickets.userId and users.id, now I wrote some functions on models:

User model:

public function tickets()
{
    return $this->hasMany('App\Tickets');
}

Tickets model:

public function user()
{
    return $this->belongsTo('App\User');
}

This code as dd(\App\Tickets::with('user')->get()); return null on relation result, for example:

0 => Tickets {#209 ▼
  #table: "tickets"
  #connection: null
  #primaryKey: "id"
  #keyType: "int"
  #perPage: 15
  +incrementing: true
  +timestamps: true
  #attributes: array:9 [▶]
  #original: array:9 [▶]
  #relations: array:1 [▼
    "user" => null
  ]

Upvotes: 0

Views: 56

Answers (2)

Sanzeeb Aryal
Sanzeeb Aryal

Reputation: 3266

Your relation assumes that the user_id as the foreign key as default. you may also override the foreign and local keys by passing additional arguments to the hasMany method:

return $this->hasMany('App\Ticket', 'foreign_key', 'local_key');

so,

User Model:

public function tickets()
    {
        return $this->hasMany('App\Ticket','userId','id');
    }

Ticket Model:

public function user()
{
    return $this->belongsTo('App\User','userId','id');
}

Upvotes: 1

Erik
Erik

Reputation: 555

In your tickets model it should be

public function user()
{
    return $this->belongsTo('App\User', 'userId');
}

The default foreign key laravel is searching for is model_id. And a little side note: it's a common best practice to use it's single verb, so tickets should be Ticket.

Upvotes: 0

Related Questions