gpt4 book ai didi

mysql - laravel 三个用户、类、表、文章的查询预览

转载 作者:行者123 更新时间:2023-11-29 16:28:00 25 4
gpt4 key购买 nike

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

数据库架构:

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');
}

Controller 类别

 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'));}

最佳答案

在您的 Controller 中,您可以使用以下代码:

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));
}

为了使这些功能正常工作,您需要将这些方法添加到您的用户模型中:

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

关于mysql - laravel 三个用户、类、表、文章的查询预览,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54131282/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com