user10811118
user10811118

Reputation:

Laravel belongsTo ignoring foreign key

I have 2 models, User and Task.

Task.php:

<?php

namespace App;

use Illuminate\Database\Eloquent\Model;

class Task extends Model
{
    //  
   protected $fillable=['text','title','user_id','completed','created_by'];
   public function users()
   {
        return $this->belongsTo(User::class, 'id');
   }

}

and User.php:

<?php

namespace App;

use Illuminate\Notifications\Notifiable;
use Illuminate\Contracts\Auth\MustVerifyEmail;
use Illuminate\Foundation\Auth\User as Authenticatable;

class User extends Authenticatable
{
    use Notifiable;

    /**
     * The attributes that are mass assignable.
     *
     * @var array
     */
    protected $fillable = [
        'name', 'email', 'password',
    ];

    /**
     * The attributes that should be hidden for arrays.
     *
     * @var array
     */
    protected $hidden = [
        'password', 'remember_token',
    ];
    public function tasks()
    {
        return $this->hasMany(Task::class);
    }
}

My objective here is to have every task assigned to a user so I can retrieve the name of the user that created that task.
The users table has id and name columns. The task table also has an id column.
So how can I get the name of the user that created a task using eloquent relationships?

App\User::first()->tasks

gives:

Illuminate/Database/QueryException with message 'SQLSTATE[42S22]: Column not found: 1054 Unknown column 'tasks.user_id' in 'where clause' (SQL: select * from `tasks` where `tasks`.`user_id` = 1 and `tasks`.`user_id` is not null)'

Upvotes: 2

Views: 790

Answers (3)

Jems
Jems

Reputation: 1706

Maybe the problem is in your Task model

public function users()
{
   return $this->belongsTo(User::class, 'user_id');
}

I saw the documentation and Laravel uses foreign_key as the second parameter, not primary_key as second parameter

Upvotes: 0

guizo
guizo

Reputation: 3095

You said "My objective here is to have every task assigned to a user..." so I belive one task belongs to one user only. If that is the case it is indeed a One to Many relationship. You should call user() not users() on the Task model:

public function user()
{
    return $this->belongsTo(User::class);
}

Upvotes: 0

user10811118
user10811118

Reputation:

To solve this I added this function to Task.php

 public function users()
   {
        return $this->belongsTo(User::class, 'created_by');
   }

I wasn't supposed to use 'id' as foreign key. And also removed

 public function tasks()
    {
        return $this->hasMany(Task::class);
    }

from User model.

Upvotes: 1

Related Questions