Laravel introductory tutorial: The relationship between tables
##First of all, about the relationship between tables
1.One-to-one2.One-to-many3.Many-to-one4.Many-to-manyDistinguish between parent table and child table
1. The "one" side is the parent table2. The "many" side It is a child tableHow to deal with one-to-many relationships
Create a field (foreign key) in the child table to point to the parent table
How to deal with many-to-many relationships
Create an intermediate table to convert the "many-to-many" relationship into "one-to-many"
Case analysis
Table 1: User table (it_user)Table 2: User details table (it_user_info)Table 3: Article table (it_article)Table 4: Country table (it_country)Table 5: User role table (it_role)① One-to-oneThe user table (Table 1) and the details table (Table 2) have a one-to-one relationship②One-to-manyThe user table (Table 1) and the article table ( Table 3) is a one-to-many relationship③Many-to-oneThe user table (Table 1) and the country table (Table 4) are a many-to-one relationship ④Many-to-manyThe user table (Table 1) and the role table (Table 5) are a many-to-many relationshipUser table creation and test data
DROP TABLE IF EXISTS `it_user`; CREATE TABLE `it_user` ( `id` int(10) unsigned NOT NULL AUTO_INCREMENT COMMENT '主键', `name` varchar(64) DEFAULT NULL COMMENT '用户名', `password` char(32) DEFAULT NULL COMMENT '密码(不使用md5)', `country_id` int(11) DEFAULT NULL, PRIMARY KEY (`id`), KEY `国家id` (`country_id`) ) ENGINE=MyISAM AUTO_INCREMENT=6 DEFAULT CHARSET=utf8; -- ---------------------------- -- Records of it_user -- ---------------------------- INSERT INTO `it_user` VALUES ('1', 'xiaoming', '123456', '1'); INSERT INTO `it_user` VALUES ('2', 'xiaomei', '123456', '1'); INSERT INTO `it_user` VALUES ('3', 'xiaoli-new', '123', '1');
User details table creation and test data
-- ---------------------------- -- Table structure for it_user_info -- ---------------------------- DROP TABLE IF EXISTS `it_user_info`; CREATE TABLE `it_user_info` ( `user_id` int(11) NOT NULL AUTO_INCREMENT, `tel` char(11) DEFAULT NULL, `email` varchar(128) DEFAULT NULL, `addr` varchar(255) DEFAULT NULL, PRIMARY KEY (`user_id`) ) ENGINE=MyISAM AUTO_INCREMENT=4 DEFAULT CHARSET=utf8; -- ---------------------------- -- Records of it_user_info -- ---------------------------- INSERT INTO `it_user_info` VALUES ('1', '13012345678', 'xiaoming@163.com', '北京'); INSERT INTO `it_user_info` VALUES ('2', '15923456789', 'xiaomei@163.com', '上海'); INSERT INTO `it_user_info` VALUES ('3', '18973245670', 'xiaoli@163.com', '武汉');
Article table creation and test data
-- ---------------------------- -- Table structure for it_article -- ---------------------------- DROP TABLE IF EXISTS `it_article`; CREATE TABLE `it_article` ( `id` int(11) NOT NULL AUTO_INCREMENT, `title` varchar(255) DEFAULT NULL, `content` text, `user_id` int(11) DEFAULT NULL, PRIMARY KEY (`id`), KEY `user_id` (`user_id`) ) ENGINE=MyISAM AUTO_INCREMENT=4 DEFAULT CHARSET=utf8; -- ---------------------------- -- Records of it_article -- ---------------------------- INSERT INTO `it_article` VALUES ('1', '世界那么大,我想去看看', '钱包那么小,总是不够', '1'); INSERT INTO `it_article` VALUES ('2', '我想撞角遇到爱', '却是碰到鬼', '2'); INSERT INTO `it_article` VALUES ('3', '哈哈哈哈', '嘻嘻嘻嘻', '1');
Country Table creation and test data
-- ---------------------------- -- Table structure for it_country -- ---------------------------- DROP TABLE IF EXISTS `it_country`; CREATE TABLE `it_country` ( `id` int(11) NOT NULL AUTO_INCREMENT, `name` varchar(255) DEFAULT NULL, PRIMARY KEY (`id`) ) ENGINE=MyISAM AUTO_INCREMENT=3 DEFAULT CHARSET=utf8; -- ---------------------------- -- Records of it_country -- ---------------------------- INSERT INTO `it_country` VALUES ('1', '中国'); INSERT INTO `it_country` VALUES ('2', '美国');
User role table creation and test data
-- ---------------------------- -- Table structure for it_role -- ---------------------------- DROP TABLE IF EXISTS `it_role`; CREATE TABLE `it_role` ( `id` int(11) NOT NULL AUTO_INCREMENT, `name` varchar(255) DEFAULT NULL, PRIMARY KEY (`id`) ) ENGINE=MyISAM AUTO_INCREMENT=5 DEFAULT CHARSET=utf8; -- ---------------------------- -- Records of it_role -- ---------------------------- INSERT INTO `it_role` VALUES ('1', '开发'); INSERT INTO `it_role` VALUES ('2', '测试'); INSERT INTO `it_role` VALUES ('3', '管理');
User and role intermediate table creation and testing Data
-- ---------------------------- -- Table structure for it_user_role -- ---------------------------- DROP TABLE IF EXISTS `it_user_role`; CREATE TABLE `it_user_role` ( `user_id` int(11) DEFAULT NULL, `role_id` int(11) DEFAULT NULL, KEY `role_id` (`role_id`), KEY `user_id` (`user_id`) ) ENGINE=MyISAM DEFAULT CHARSET=utf8; -- ---------------------------- -- Records of it_user_role -- ---------------------------- INSERT INTO `it_user_role` VALUES ('1', '1'); INSERT INTO `it_user_role` VALUES ('1', '2'); INSERT INTO `it_user_role` VALUES ('1', '3'); INSERT INTO `it_user_role` VALUES ('2', '1'); INSERT INTO `it_user_role` VALUES ('3', '2');
Preparation work
1. Planning routing
In routes/ Write the following route under web.php://ORM的关联关系 Route::get('/orm/relation/{mode}','ORM\UserController@relation');
2. Write the relation method in App/Http/Controllers/ORM/UserController.php
public function relation($mode) { switch ($mode){ case '1_1': { //一对一 } break; case '1_n': { //一对多 } break; case 'n_1': { //多对一 } break; case 'n_n': { //多对多 } break; default; } }
3. Install the debug debugging tool
3.1 Use the composer command to installcomposer require barryvdh/laravel-debugbar
Barryvdh\Debugbar\ServiceProvider::class,
\DB::listen(function ($query) { var_dump($query->sql); var_dump($query->bindings); echo '<br>'; });
One-on-one
1. Create the Userinfo model object
Enter the cmd command line. Executing the following command in the directory where the laravel project is locatedphp artisan make:model Userinfo
2. Edit the Userinfo model file
<?php namespace App; use Illuminate\Database\Eloquent\Model; class Userinfo extends Model { protected $table = 'user_info'; protected $primaryKey = 'user_id'; protected $fillable = ['user_id','tel','email','addr']; public $timestamps = false; }
3. Write UserModel and add one-to-one method
<?php namespace App; use Illuminate\Database\Eloquent\Model; class UserModel extends Model { protected $table = 'user';//真是表名 protected $primaryKey = 'id';//主键字段,默认为id protected $fillable = ['name','password'];//可以操作的字段 public $timestamps = false;//如果数据表中没有created_at和updated_id字段,则$timestamps则可以不设置, 默认为true public function Userinfo() { /* * @param [string] [name] [需要关联的模型类名] * @param [string] [foreign] [参数一指定数据表中的字段] * */ return $this->hasOne('App\Userinfo','user_id'); }
4. Write UserController and call one-to-one method
public function relation($mode) { switch ($mode){ case '1_1': { //一对一 $data = UserModel::find(1)->Userinfo()->get(); dd($data); } break; default; } }
One-to-many
1. Create the article model object
Execute the commandphp artisan make:model Article
2. Write article model file
<?php namespace App; use Illuminate\Database\Eloquent\Model; class Article extends Model { protected $table = 'article'; protected $primaryKey = 'id'; protected $fillable = ['id','title','content','user_id']; public $timestamps = false; }
3. Write UserModel and add one-to-many method
public function Artice() { return $this->hasMany('App\Article','User_id'); }
4. Write UserController and call one-to-many method
public function relation($mode) { switch ($mode){ case '1_1': { //一对一 $data = UserModel::find(1)->Userinfo()->get(); dd($data); } break; case '1_n': { //一对多 $data = UserModel::find(1)->Artice()->get(); dd($data); } break; default; } } }
many-to-one
1. Create country model Object
executes the commandphp artisan make:model Country
2. Write the country model file
<?php namespace App; use Illuminate\Database\Eloquent\Model; class Country extends Model { protected $table = 'country'; //真实表名 protected $primaryKey = "id"; //主键id protected $fillable = ['id','name']; //允许操作的字段 public $timestamps = false; //如果数据表中没有created_at和updated_id字段,则$timestamps则可以不设置, 默认为true }
3. Write the UserModel and add many-to-one Method
public function Country() { return $this->belongsTo('App\Country','country_id'); }
4. Write UserController and call method
public function relation($mode) { switch ($mode){ case '1_1': { //一对一 $data = UserModel::find(1)->Userinfo()->get(); dd($data); } break; case '1_n': { //一对多 $data = UserModel::find(1)->Artice()->get(); dd($data); } break; case 'n_1': { //多对一 $data = UserModel::find(1)->Country()->get(); dd($data); } break; default; } } }
Many-to-Many
1. Create role model object
Execute commandphp artisan make:model Role
php artisan make:model User_role
2.Write Role model
<?php namespace App; use Illuminate\Database\Eloquent\Model; class Role extends Model { protected $table = 'role'; protected $primaryKey = "id"; protected $fillable = ['name']; public $timestamps =false; }
<?php namespace App; use Illuminate\Database\Eloquent\Model; class User_role extends Model { protected $table = 'user_role'; public $timestamps =false; }
3. Write the UserModel and add the many-to-many method
public function Role(){ /* * 第一个参数:要关联的表对应的类 * 第二个参数:中间表的表名 * 第三个参数:当前表跟中间表对应的外键 * 第四个参数:要关联的表跟中间表对应的外键 * */ return $this->belongsToMany('App\Role','user_role','user_id','role_id'); }
4. Write UserController and call the many-to-many method
public function relation($mode) { switch ($mode){ case '1_1': { //一对一 $data = UserModel::find(1)->Userinfo()->get(); dd($data); } break; case '1_n': { //一对多 $data = UserModel::find(1)->Artice()->get(); dd($data); } break; case 'n_1': { //多对一 $data = UserModel::find(1)->Country()->get(); dd($data); } break; case 'n_n': { //多对多 $data = UserModel::find(2)->Role()->get(); dd($data); } break; default; } }
Summary:
1. One pair One usage method: hasOne()2. One-to-many usage method: hasMany()3. Many-to-one usage method: belongsTo()4. Many How to use many: belongsToMany()PHP Chinese website, a large number of freelaravel introductory tutorials, welcome to learn online!
This article is reproduced from: https://blog.csdn.net/weixin_38112233/article/details/79220535The above is the detailed content of Laravel introductory tutorial: The relationship between tables. For more information, please follow other related articles on the PHP Chinese website!

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics











Laravel is a PHP framework for easy building of web applications. It provides a range of powerful features including: Installation: Install the Laravel CLI globally with Composer and create applications in the project directory. Routing: Define the relationship between the URL and the handler in routes/web.php. View: Create a view in resources/views to render the application's interface. Database Integration: Provides out-of-the-box integration with databases such as MySQL and uses migration to create and modify tables. Model and Controller: The model represents the database entity and the controller processes HTTP requests.

When developing websites using CraftCMS, you often encounter resource file caching problems, especially when you frequently update CSS and JavaScript files, old versions of files may still be cached by the browser, causing users to not see the latest changes in time. This problem not only affects the user experience, but also increases the difficulty of development and debugging. Recently, I encountered similar troubles in my project, and after some exploration, I found the plugin wiejeben/craft-laravel-mix, which perfectly solved my caching problem.

Want to learn the Laravel framework, but suffer from no resources or economic pressure? This article provides you with free learning of Laravel, teaching you how to use resources such as online platforms, documents and community forums to lay a solid foundation for your PHP development journey from getting started to master.

Laravel provides a comprehensive Auth framework for implementing user login functions, including: Defining user models (Eloquent model), creating login forms (Blade template engine), writing login controllers (inheriting Auth\LoginController), verifying login requests (Auth::attempt) Redirecting after login is successful (redirect) considering security factors: hash passwords, anti-CSRF protection, rate limiting and security headers. In addition, the Auth framework also provides functions such as resetting passwords, registering and verifying emails. For details, please refer to the Laravel documentation: https://laravel.com/doc

Article summary: This article provides detailed step-by-step instructions to guide readers on how to easily install the Laravel framework. Laravel is a powerful PHP framework that speeds up the development process of web applications. This tutorial covers the installation process from system requirements to configuring databases and setting up routing. By following these steps, readers can quickly and efficiently lay a solid foundation for their Laravel project.

In the Laravel framework version selection guide for beginners, this article dives into the version differences of Laravel, designed to assist beginners in making informed choices among many versions. We will focus on the key features of each release, compare their pros and cons, and provide useful advice to help beginners choose the most suitable version of Laravel based on their skill level and project requirements. For beginners, choosing a suitable version of Laravel is crucial because it can significantly impact their learning curve and overall development experience.

The Laravel framework has built-in methods to easily view its version number to meet the different needs of developers. This article will explore these methods, including using the Composer command line tool, accessing .env files, or obtaining version information through PHP code. These methods are essential for maintaining and managing versioning of Laravel applications.

Laravel and ThinkPHP are both popular PHP frameworks and have their own advantages and disadvantages in development. This article will compare the two in depth, highlighting their architecture, features, and performance differences to help developers make informed choices based on their specific project needs.
