Eloquent 关系 Laravel 5

Eloquent relationship Laravel 5

我有两个模型。文章和用户。在文章中我有这个功能

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

用户有此功能

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

在 git bash 给出 php artisan tinker 命令后,当我给出 App\Article::first();

显示数据库的第一篇文章。

$user=App\User::first();

此命令可以显示第一个用户。

但是当我给

 $user->articles->toArray();

这个命令显示

 [Symfony\Component\Debug\Exception\FatalThrowableError]
  Call to a member function toArray() on null

但按照教程所示,它应该显示用户 1 的文章。

有两个原因:

1 aritcles 没有外键名称 user_id 引用 user 模型

2 由于外键未命名为 user_id 您必须在定义关系时显式定义外键名称。

public function user(){
    return $this->belongsTo('App\User','foreign_key');
}    
public function articles(){    
 return $this->hasMany('App\Article','foreign_key');
}

为了获取文章,users table 应该有一个 article_id 字段或者 articles table 应该有一个 user_id 字段。此外,您 return 的第一篇文章,请尝试 $article->user 并检查正在 return 编辑的 user

您报告的错误是因为没有文章与给定用户关联。换句话说,这篇文章没有 user_id 设置为当前用户的 id。

Eloquent:laravel

的关系

1.一对多

假设 1 用户有很多文章

在用户模型中:

 public function user()
    {
        return $this->hasMany('App\Article','user_id');
    }

在文章模型中

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

获取属于用户的所有文章

$user = App\User::with('articles')->get();
$articles = $user->articles;

希望对你有帮助!