开发者社区> 问答> 正文

如何通过Laravel雄辩的模型加入三张桌子?mysql

我有三张桌子

物品表 id title body categories_id user_id 分类表 id category_name 用户表 id user_name user_type 我想显示其类别名称而不是category_id和user_name而不是user_id的文章,我尝试像这些查询一样工作!

$articles =DB::table('articles') ->join('categories', 'articles.id', '=', 'categories.id') ->join('users', 'users.id', '=', 'articles.user_id') ->select('articles.id','articles.title','articles.body','users.username', 'category.name') ->get(); 但是我想用口才来做。拜托,我该怎么办?

展开
收起
保持可爱mmm 2020-05-17 18:43:58 354 0
1 条回答
写回答
取消 提交回答
  • 使用Eloquent,它非常容易检索关系数据。在Laravel 5中使用您的场景检查以下示例。

    我们有三种模型:

    1)文章(属于用户和类别)

    2)类别(有很多文章)

    3)用户(有很多文章)

    1)Article.php

    belongsTo('App\Models\User'); } public function category() { return $this->belongsTo('App\Models\Category'); } } 2)Category.php hasMany('App\Models\Article'); } } 3)User.php hasMany('App\Models\Article'); } } 您需要了解数据库关系和模型中的设置。用户有很多文章。类别有很多文章。文章属于用户和类别。一旦在Laravel中设置了关系,就可以轻松检索相关信息。 例如,如果要使用用户和类别检索文章,则需要编写: $article = \App\Models\Article::with(['user','category'])->first(); 您可以这样使用: //retrieve user name $article->user->user_name //retrieve category name $article->category->category_name 在另一种情况下,您可能需要检索类别中的所有文章,或检索特定用户的所有文章。您可以这样写: $categories = \App\Models\Category::with('articles')->get(); $users = \App\Models\Category::with('users')->get(); 您可以在http://laravel.com/docs/5.0/eloquent了解更多来源:stack overflow
    2020-05-17 18:47:07
    赞同 展开评论 打赏
问答排行榜
最热
最新

相关电子书

更多
搭建电商项目架构连接MySQL 立即下载
搭建4层电商项目架构,实战连接MySQL 立即下载
PolarDB MySQL引擎重磅功能及产品能力盛大发布 立即下载

相关镜像