LARAVEL 5.4访问来自其他课程

时间:2017-04-10 20:26:52

标签: laravel-5 eloquent

如何从另一个对象的实例访问用户对象? 我可以访问用户的项目,但不能访问项目的 author

这:

$user_id = App\Project::find(1)->user_id;
$user = App\User::find($user_id);

返回用户

但是这个:

$user  = App\Project::find(1)->author;

返回null

预期行为:获取用户

用户类:     

namespace App;

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

class User extends Authenticatable
{
use Notifiable;

protected $fillable = [
    'name', 'email', 'password'
];

protected $hidden = [
    'password', 'remember_token',
];

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

项目类:

<?php

namespace App;

use Illuminate\Database\Eloquent\Model;

class Project extends Model
{
protected $fillable = [
    'title', 'content'
];

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

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

1 个答案:

答案 0 :(得分:0)

在您的项目模型中更改此内容:

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

到此:

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

Laravel搜索名为关系名称加_id的外键,在您的代码中搜索author_id,如果添加第二个参数,则将其更改为搜索user_id }