查询三个用户,类,表,文章laravel的预览

时间:2019-01-10 14:53:41

标签: mysql laravel laravel-5.2 laravel-5.6

我有一个记录器用户,仅想显示该用户的文章,类别。

数据库架构:

Users:    category:    article:
  id      id           id
  name    name         title
          users_id     categories_id

用户模型

class User extends Model

public function Category
{
    return $this->hasMany(Category::class,'users_id');
}

类别模型(有效)

class Category extends Model
{
    public function article
    {
        return $this->hasMany(Article::class );
    }

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

文章模型(有效)

class Article extends Model
{
    public function category()
    {
        return $this->belongsTo(Category::class,'categories_id');
    }

控制器类别

 class CategoryController extends Controller
 {
     public function index()
     {
         $categories = Category::all();
         return view('category. view', compact('categories'));
     }

 class Article Controller extends Controller
 {
     public function index()
     {
         $articles = Article::all();
         return view(' article . index', compact('articles'));}

1 个答案:

答案 0 :(得分:0)

在您的控制器中,您可以使用以下代码:

public function getArticles(){
      $user = auth()->user();
      $articles = $user->articles;
      return view('articlesView',array('articles' => $articles));
}
    public function getCategories(){
      $user = auth()->user();
      $articles = $user->categories;
      return view('categoryView',array('articles' => $articles));
}

要使这些功能起作用,您需要将以下方法添加到您的User模型中:

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