栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 面试经验 > 面试问答

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

面试问答 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

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

使用Eloquent,它非常容易检索关系数据。在Laravel 5中使用您的场景检查以下示例。

我们有三种模型:

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

2)类别(有很多文章)

3)用户(有很多文章)


1)Article.php

<?phpnamespace AppModels; use Eloquent;class Article extends Eloquent{    protected $table = 'articles';    public function user()    {        return $this->belongsTo('AppModelsUser');    }    public function category()    {        return $this->belongsTo('AppModelsCategory');    }}

2)Category.php

<?phpnamespace AppModels;use Eloquent;class Category extends Eloquent{    protected $table = "categories";    public function articles()    {        return $this->hasMany('AppModelsArticle');    }}

3)User.php

<?phpnamespace AppModels;use Eloquent;class User extends Eloquent{    protected $table = 'users';    public function articles()    {        return $this->hasMany('AppModelsArticle');    }}

您需要了解数据库关系和模型中的设置。用户有很多文章。类别有很多文章。文章属于用户和类别。一旦在Laravel中设置了关系,就可以轻松检索相关信息。

例如,如果要使用用户和类别检索文章,则需要编写:

$article = AppModelsArticle::with(['user','category'])->first();

您可以这样使用:

//retrieve user name $article->user->user_name//retrieve category name $article->category->category_name

在另一种情况下,您可能需要检索类别中的所有文章,或检索特定用户的所有文章。您可以这样写:

$categories = AppModelsCategory::with('articles')->get();$users = AppModelsCategory::with('users')->get();

您可以在http://laravel.com/docs/5.0/eloquent了解更多



转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/386420.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号