搜索
首页php框架Laravel详细解析Laravel Model模型关联

本篇文章给大家带来了关于laravel的相关知识,其中主要介绍了关于Model模型关联的相关问题,包括了一对一、一对多、多对多等内容,下面一起来看一下,希望对大家有帮助。

详细解析Laravel Model模型关联

【相关推荐:laravel视频教程

定义关联关系

数据库表通常相互关联。
例如,一篇博客文章可能有许多评论,或者一个订单对应一个下单用户。Eloquent 让这些关联的管理和使用变得简单,并支持多种类型的关联:常见的为前三种,在此我们也只讲解前三种关联

  • 一对一
  • 一对多
  • 多对多
  • 远程一对多
  • 远程一对一
  • 一对一(多态关联)
  • 一对多(多态关联)
  • 多对多

建立模型关联

一对一

示例:
两个数据表:guest 用户表和guestinfo用户信息
其中guest表中的主键id字段对应着guestinfo中的外键user_id字段
首先创建两个model文件:
php artisan make:model Guest
php artisan make:model Guestinfo
Guest model文件:

class Guest extends Model{
    use HasFactory;
    // 设置Guest模型对应的数据表
    protected $table = 'guest';
    // 关闭create_time和update_time字段自动管理
    public $timestamps = false;
    // 设置与guestinfo的关联方法,方法名建议使用被关联表的名字
    public function guestinfo(){
    // hasOne(被关联的名命空间,关联外键,关联的主键)
        return $this->hasOne('App\Models\Guestinfo','user_id','id');
    }}

Guestinfo model文件:

class Guestinfo extends Model{
    use HasFactory;
    // 设置Guest模型对应的数据表
    protected $table = 'guestinfo';
    // 关闭create_time和update_time字段自动管理
    public $timestamps = false;
    // 设置与guestinfo的关联方法,方法名建议使用被关联表的名字
    public function guest(){
    // hasOne(被关联的名命空间,关联外键,关联的主键)
        return $this->belongsTo('App\Models\Guest','user_id','id');
    }}

创建一个控制器将两个model文件连接起来:
php artisan make:controller Controllers
内容:

class Controllers extends Controller{
    //
    public function getOne(){
    // 通过关联方法获取guest表中username = admin记录在guestinfo对应的记录
    // ->guestinfo 是Guest模型文件里面定义的guestinfo方法
        $guestInfo = Guest::firstWhere('username','admin')->guestinfo;
	// 通过关联方法获取guestinfo中id=3 记录在guest表中的对应记录
        $data = Guestinfo::find(3)->guest;
        
        dump($guestInfo);
        // 将模型转换成数组
        dump($data->toArray());
    }}

创建控制器的路由:
Route::get('relative/getOne',[Controllers::class,'getOne']);
访问路由:
结果为:
在这里插入图片描述

一对多

示例:
两个数据表:guest 用户表和article文章表
其中guest表中的主键id字段对应着guestinfo中的外键user_id字段
创建articlemodel文件:
php artisan make:model Article

class Article extends Model{
    use HasFactory;
    // 设置Guest模型对应的数据表
    protected $table = 'article';
	// 关闭create_time和update_time字段自动管理    
    public $timestamps = false;
    public function guest(){
    // 设置与guest的关联方法,与一对一的从表设置一样
        return $this->belongsTo('App\Models\April\Guest','user_id','id');
    }}

Guest model文件中添加一个article 方法

class Guest extends Model{
    use HasFactory;
    // 设置Guest模型对应的数据表
    protected $table = 'guest';
    // 关闭create_time和update_time字段自动管理
    public $timestamps = false;
    // 设置与guestinfo的关联方法,方法名建议使用被关联表的名字
    public function guestinfo(){
    // hasOne(被关联的名命空间,关联外键,关联的主键)
        return $this->hasOne('App\Models\Guestinfo','user_id','id');
    }
    // 设置与article的关联:hasmany 有很多
     public function article(){
        return $this->hasMany('App\Models\April\Article','user_id','id');
    }}

Controllers 控制器文件中测试一下:
实例1:查询某一个用户发表的所有文章:

 		// 查询某个用户发表的所有文章
        $article = Guest::find(1)->article;
        // 返回为数据集,需要遍历
        foreach ($article as $v){
            dump($v->toArray());
        }

在这里插入图片描述

实例2:查询某个用户最新发表的一篇文章

		// 查询某个用户最新发表的一篇文章
        // article()生成一个构造器,可以进行筛选
        $article = Guest::find(1)->article()->orderby('created_at','desc')->first();
        dump($article->toArray());

在这里插入图片描述
实例3:通过关联查询某篇文章的发表人的姓名

		//  通过article和guest关联,再通过guest关联的guestinfo获取姓名
        $name = Article::find(2)->guest->guestinfo;
        dump($name->name);

实例4:通过关联查询某篇文章的评论信息
创建Comment评论模型:
php artisan make:model Comment
Comment 模型代码:

class Comment extends Model{
    use HasFactory;
    // 设置Comment模型对应的数据表
    protected $table = 'comment';
    // 关闭create_time和update_time字段自动管理
    public $timestamps = false;
    // 设置与article的关联方法,方法名建议使用被关联表的名字
    public function article(){
        return $this->belongsTo('App\Models\April\Article','article_id','id');
    }}

在Article模型中添加方法comment:

public function comment(){
        return $this->hasMany('App\Models\April\Comment','article_id','id');
    }

controller控制器代码:

$info = Article::find(2)->comment;
        foreach ($info as $v){
            dump($v->toArray());
        }

在这里插入图片描述

【相关推荐:laravel视频教程

以上是详细解析Laravel Model模型关联的详细内容。更多信息请关注PHP中文网其他相关文章!

声明
本文转载于:CSDN。如有侵权,请联系admin@php.cn删除
包容的幻想:解决偏远工作中的孤立和孤独感包容的幻想:解决偏远工作中的孤立和孤独感Apr 25, 2025 am 12:28 AM

Tocombatisolationandlonelinessinremotework,companiesshouldimplementregular,meaningfulinteractions,provideequalgrowthopportunities,andusetechnologyeffectively.1)Fostergenuineconnectionsthroughvirtualcoffeebreaksandpersonalsharing.2)Ensureremoteworkers

Laravel用于全堆栈开发:综合指南Laravel用于全堆栈开发:综合指南Apr 25, 2025 am 12:27 AM

laravelispularfullull-stackDevelopmentBecapeitOffersAsAseAseAseAseBlendOfbackendEdpoperandPowerandForterFlexibility.1)ITSbackEndCapaPabilities,sightifyDatabaseInteractions.2)thebladeTemplatingEngingEngineAllolowsLows

视频会议摊牌:为远程会议选择正确的平台视频会议摊牌:为远程会议选择正确的平台Apr 25, 2025 am 12:26 AM

选择视频会议平台的关键因素包括用户界面、安全性和功能。1)用户界面应直观,如Zoom。2)安全性需重视,MicrosoftTeams提供端到端加密。3)功能需匹配需求,GoogleMeet适合简短会议,CiscoWebex提供高级协作工具。

哪些数据库版本与最新的Laravel兼容?哪些数据库版本与最新的Laravel兼容?Apr 25, 2025 am 12:25 AM

最新版本的Laravel10与MySQL5.7及以上、PostgreSQL9.6及以上、SQLite3.8.8及以上、SQLServer2017及以上兼容。这些版本选择是因为它们支持Laravel的ORM功能,如MySQL5.7的JSON数据类型,提升了查询和存储效率。

将Laravel用作全栈框架的好处将Laravel用作全栈框架的好处Apr 25, 2025 am 12:24 AM

laravelisanexceltentchoiceforfull-stackdevelopmentduetoitsRobustFeaturesAndEsofuse.1)ITSImplifiesComplexComplextaskSwithitSmodernphpsyNtaxandToolSandToolSlikeBlikeforFront-Endandeloquentormquentormquentormforback-end.2)

Laravel的最新版本是什么?Laravel的最新版本是什么?Apr 24, 2025 pm 05:17 PM

Laravel10,releasedonFebruary7,2023,isthelatestversion.Itfeatures:1)Improvederrorhandlingwithanewreportmethodintheexceptionhandler,2)EnhancedsupportforPHP8.1featureslikeenums,and3)AnewLaravel\Promptspackageforinteractivecommand-lineprompts.

最新的Laravel版本如何简化开发?最新的Laravel版本如何简化开发?Apr 24, 2025 pm 05:01 PM

thelatestlaravelververversionenhancesdevelopmentwith:1)简化的inimpliticmodelbinding,2)增强EnhancedeloquentcapabibilitionswithNewqueryMethods和3)改善了supportorfortormodernphpfortornphpforternphpfeatureserslikenamedargenamedArgonedArgonsemandArgoctess,makecodingMoreftermeforefterMealiteFficeAndEnjoyaigaigaigaigaigaiganigaborabilyaboipaigyAndenjoyaigobyabory。

在哪里可以找到最新的Laravel版本的发行说明?在哪里可以找到最新的Laravel版本的发行说明?Apr 24, 2025 pm 04:53 PM

你可以在laravel.com/docs找到最新Laravel版本的发布说明。1)发布说明提供了新功能、错误修复和改进的详细信息。2)它们包含示例和解释,帮助理解新功能的应用。3)注意新功能的潜在复杂性和向后兼容性问题。4)定期审查发布说明可以保持更新并激发创新。

See all articles

热AI工具

Undresser.AI Undress

Undresser.AI Undress

人工智能驱动的应用程序,用于创建逼真的裸体照片

AI Clothes Remover

AI Clothes Remover

用于从照片中去除衣服的在线人工智能工具。

Undress AI Tool

Undress AI Tool

免费脱衣服图片

Clothoff.io

Clothoff.io

AI脱衣机

Video Face Swap

Video Face Swap

使用我们完全免费的人工智能换脸工具轻松在任何视频中换脸!

热工具

WebStorm Mac版

WebStorm Mac版

好用的JavaScript开发工具

DVWA

DVWA

Damn Vulnerable Web App (DVWA) 是一个PHP/MySQL的Web应用程序,非常容易受到攻击。它的主要目标是成为安全专业人员在合法环境中测试自己的技能和工具的辅助工具,帮助Web开发人员更好地理解保护Web应用程序的过程,并帮助教师/学生在课堂环境中教授/学习Web应用程序安全。DVWA的目标是通过简单直接的界面练习一些最常见的Web漏洞,难度各不相同。请注意,该软件中

SublimeText3 英文版

SublimeText3 英文版

推荐:为Win版本,支持代码提示!

EditPlus 中文破解版

EditPlus 中文破解版

体积小,语法高亮,不支持代码提示功能

记事本++7.3.1

记事本++7.3.1

好用且免费的代码编辑器