K
K
kfedor2017-02-24 11:58:00
Laravel
kfedor, 2017-02-24 11:58:00

How to set up User Model relationships in Laravel 5.4?

There are two models. User (derived from make:auth ) and Ad . The Ad model inherits Model , and the User model inherits Authenticatable .
As a result, when I try to assign relationships between models, I get an error:

General error: 1364 Field 'user_id' doesn't have a default value

Model Ad has the function:
public function user()
    {
        return $this->belongsTo('App\User');
    }

The User model has a function:
public function ads()
    {
        return $this->hasMany('App\Ad');
    }

What is the problem and how to solve?
PS
Full Model Users:
<?php

namespace App;

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

class User extends Authenticatable
{
    public function ads()
    {
        return $this->hasMany('App\Ad');
    }

    use Notifiable;

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

    /**
     * The attributes that should be hidden for arrays.
     *
     * @var array
     */
    protected $hidden = [
        'password', 'remember_token',
    ];
}

Ad:
<?php

namespace App;

use Illuminate\Database\Eloquent\Model;

class Ad extends Model
{
    public function category()
    {
        return $this->belongsTo('App\Category');
    }

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

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

The ads table contains a user_id field .

Answer the question

In order to leave comments, you need to log in

3 answer(s)
A
Alexander Pushkarev, 2017-02-24
@AXP-dev

Does the ads table have a user_id column?

M
Maxim Timofeev, 2017-02-24
@webinar

https://yandex.ru/search/?text=doesn%27t%20have%20...

J
junart, 2017-02-26
@junart

Try explicitly specifying keys in models

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question