Warning: file_get_contents(/data/phpspider/zhask/data//catemap/0/laravel/10.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Php Laravel 4-检索属于另一个表的字段值时未定义的属性_Php_Laravel - Fatal编程技术网

Php Laravel 4-检索属于另一个表的字段值时未定义的属性

Php Laravel 4-检索属于另一个表的字段值时未定义的属性,php,laravel,Php,Laravel,我试图在我的文章(REST)控制器中获取“用户”表的“名称”字段。 这些是我的模型: // models/Article.php class Article extends Eloquent { protected $fillable = []; protected $table = 'articles'; public function user(){ return $this->belongsTo('User','user_id'); }

我试图在我的文章(REST)控制器中获取“用户”表的“名称”字段。 这些是我的模型:

// models/Article.php

class Article extends Eloquent {
    protected $fillable = [];

    protected $table = 'articles';

    public function user(){

    return $this->belongsTo('User','user_id');
    }

    public function upload(){

    return $this->has_one('Upload');
    }
}


// models/User.php

class User extends Eloquent implements UserInterface, RemindableInterface {

    use UserTrait, RemindableTrait;


    protected $fillable = array('email','password','name');

    public function articles(){

    return $this->hasMany('Article','user_id');
    }

    /**
    * Get the unique identifier for the user.
    *
    * @return mixed
    */
    public function getAuthIdentifier()
    {
      return $this->getKey();
    }

    public function getAuthPassword()
    {
      return $this->password;
    }

    public function getReminderEmail()
    {
      return $this->email;
    }

    /**
    * The database table used by the model.
    *
    * @var string
    */
    protected $table = 'users';

    /**
    * The attributes excluded from the model's JSON form.
    *
    * @var array
    */
    protected $hidden = array('password', 'remember_token');
}



// controllers/ArticlesController.php

class ArticlesController extends \BaseController {
    public function index() // GET (all)
    {
        $articles =  Article::all();
        foreach ($articles as $article) {
            // ** ERROR ** Undefined property: Illuminate\Database\Eloquent\Relations\BelongsTo::$id
            var_dump("title: ".$article->titulo." | user: ".$article->user()->id .' | email: '.$article->user()->email );
        }
    }

    // other functions [....]
}
那么..如何正确地从“用户”表中获取字段??我一直在搜索Laravel博士和这个网站。。。我没有找到错误:(


我已经在迁移文件上设置了数据库关系,并且查看了mysql数据库关系图,一切正常。

您是否正确检查了键。
belongsTo
的第二个参数应该是本地键,而
hasMany
的第二个参数是外键。

是的,我有//articles(table)id(PK)bigint unsigned,title,description,user_id(FK)bigint unsigned//users(table)id(PK)bigint unsigned,email,nameTry this
$this->belongsTo('user','user_id','id');