当前位置:网站首页>Examples of how laravel uses with preload (eager to load) and nested query
Examples of how laravel uses with preload (eager to load) and nested query
2022-06-26 12:23:00 【Special sword】
laravel Use with Preloading ( Eager to load ) Examples of how to use and nested queries
with() What method can do ? In what scenarios ?
1. The scene is as follows .2 Data sheets Main table userinfors User table 【id,name,created_at】, From table article table articles surface 【id,user_id,title,content,created_at】
3. demand : According to the current login user A obtain A Published articles .
4. The relationship between models : One to many , One user can have multiple articles .
Table structure
1. Main table (userinfors)
2. From the table (articles)
Code implementation ( According to the current login user , Get all relevant articles under the user )
1. establish model( I'm not going to go over it here )
2. In the main table model(userinfor surface ) Create a one to many relationship in the model
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
use Tests\Controllers\UserController;
/** * Front end user model * Class UserInfor * @package App\Models */
class UserInfor extends Model
{
use HasFactory;
// The table name associated with the model
protected $table = 'userinfors';
// Please fill in the drop down array for attributes that cannot be copied in batch
protected $guarded = [];
// Model serialization :Date Type conversion
protected $casts = [
'created_at' => 'date:Y-m-d H:i:s',
'updated_at' => 'date:Y-m-d H:i:s',
];
/** * User model one to many associated user dynamic table * A user has multiple pieces of dynamic data * Parameters 1: Model to associate ( From the table ) * Parameters 2: That exists in the slave table and userinfor( Main table ) Associated fields * Parameters 3: The one that exists in the main table and Field names associated from the table */
public function article_hasMany()
{
return $this->hasMany(Article::class,'user_id','id');
}
}
3. In the controller Controller To realize with
<?php
namespace App\Http\Controllers\Api\V1;
use App\Http\Controllers\BaseController;
use App\Http\Controllers\Controller;
use App\Models\Article;
use App\Models\UserInfor;
use Illuminate\Http\Request;
/** * User dynamic controller * Class UserDynamicController * @package App\Http\Controllers\Api\V1 */
class ArticleController extends Controller
{
// Get the dynamic list of currently logged in users
public function getMyDynamicList(Request $request){
// Receive the necessary parameters
$page = $request['page'] ?? 1;// Pagination
$limit = 2;// Number of data bars per page
$offset = $page * $limit - $limit;// Read from the first few The default is 0 strip
// Query the dynamic data of the current user ( Reverse order )
$user_id = UserInfor::where('id',1);// Get the currently logged in user model
// Query the articles under the current user , And paging , each page 2 Data , Arrange the articles in reverse order according to their creation time .
$data_list = $user_id->with(['article_hasMany'=>function($query) use($offset,$limit){
// Be careful : The fields called in this closure are all associated model In the field ( That is, the fields that exist in the slave table , There is no need to consider the problem that the field name of the secondary table is duplicate with that of the primary table .)
// As the following example :$query->orderBy(' From the table created_at','desc')->offset($offset)->limit($limit);
$query->orderBy('created_at','desc')->offset($offset)->limit($limit);
}])->first();
dd($data_list->toArray());//laravel The print function provided by the framework , The effect is the same as below 2 Line code .
//var_dump($data_list->toArray());
//die;
}
}
4. Return data structure
array:25 [
"id" => 1
"created_at" => null
"name" => " Liu Tong "
"articles" => array:2 [
0 => array:5 [
"id" => 2
"created_at" => "2020-10-26 10:36:59"
"user_id" => 1
"title" => " The writer A-2"
"content"=>" Content A-2 Content A-2 Content A-2 Content A-2"
]
1 => array:5 [
"id" => 1
"created_at" => "2020-10-22 12:36:59"
"user_id" => 1
"title" => " The writer A-1"
"content"=>" Content A-1 Content A-1 Content A-1 Content A-1"
]
]
]
4. summary :
In brief, why do I use this with() Method : This is because he compressed mysql Query statement , Change the query statement to 2 strip .
Article 1 check the designated user .
Article 2 check be-all Specify article .
sql To run 2 All over .
But the routine will run N+1 All over
Check the specified user for the first time .
Check the assigned articles for the second time .
The first … Look up the assigned article .
The first N Check the specified articles .
This is not very database friendly , We all know the shortcomings , I won't go into details .
5. Combat code
// Get the dynamic list of currently logged in users
public function getMyDynamicList(Request $request){
// Receive the necessary parameters
$page = $request['page'] ?? 1;// Pagination
$limit = 12;// Number of data bars per page
$offset = $page * $limit - $limit;// Read from the first few The default is 0 strip
// Query the dynamic data of the current user ( Reverse order )
$user_infor = UserInfor::where('token',$request['token']);
$data_list = $user_infor->with(['userDynamics'=>function($query) use($offset,$limit){
$query->orderBy('created_at','desc')->offset($offset)->limit($limit);
$query->withCount('userDynamicComments as connent_count');// Parameters 1, The associated method name in the model ,as * Represents the alias of the return value
$query->withCount('userDynamicAdmiress as admiress_count');
}])->select('id','nickname','pic_url')->first();
}
with Loop nesting usage
1. Use scenarios : When 3 How to write circular nesting when you want to create an association .
Take an inappropriate example !
What if : existing 3 The tables are A: Book list ,B: Comment table ,C: Reviewer phone list .
Table relations : Be careful : The same book can only be commented by the same person once !( That is, a book can have multiple comments , But the reviewer of each comment can only be associated with the book once !)
Book list ( One ) Yes Comment table ( many ) = One to many connection .
Comment table ( One ) Yes Commentator ( One ) = One to one connection .
demand : It is known that Books id And Designated comments id, Based on Books id It can be concluded by inquiry Comment content as well as Reviewer phone data
Table structure diagram :
A: Book list (book)
| id | name( Book name ) |
|---|---|
| 1 | my php file |
| 2 | My overtime history |
| 3 | My work record |
B: Comment table (comment)
| id | comment( Comment content ) | book_id( The Secretary table is related to id) | tel_id( Phone list Association id) |
|---|---|---|---|
| 1 | This book is really thick | 1 | 18 |
| 2 | My eyes are full of tears | 1 | 43 |
| 3 | Is this really a daily record ? It's very detailed | 2 | 69 |
C: Reviewer phone list (tel)
| id | comment_id( Comment table id) | tel( Reviewer phone number ) |
|---|---|---|
| 18 | 1 | 183******3645 |
| … | … | … |
| 43 | 2 | 133******2625 |
| … | … | … |
| 69 | 3 | 131******1661 |
2. Use with() The code implements circular nested queries
// According to the specified book id And Designated comments id Get current book data .
public function getBookParticulars(Request $request){
// Receiving books id
$book_id = $request->book_id;// Books id
$comment_id = $request->comment_id;// Designated comments id
//bookComment = Books Book The model defines the name of the one to many relevance review method
//commentTel = Comment content table one-to-one related reviewer telephone list
$book = Book::where('id',$book_id)->with(['bookComment'=>function($query) use ($comment_id){
//$comment_id The front end is passed to php Method parameters , need use Can be in with Use in
$query->where('comment_id',$comment_id)
#->with('commentTel:id,tel')// Nesting A In this line of code ‘id’ It's the reviewer phone list (tel) Of id, Don't write this id May result in no query results
->with(['commentTel'=>function($query2){
$query2->first();
}])// Nesting B
->first();
}])->first();
dd($book);// Print data view results
}
边栏推荐
- Cet article présente la moyenne mobile quadratique linéaire et le fonctionnement simple d'Excel pour réaliser la prédiction des séries chronologiques dans la modélisation.
- Spark-day02-core programming-rdd
- One click deployment of your own community forum
- 2021 q3-q4 investigation report on the use status of kotlin multiplatform
- One click deployment CEPH script
- 我想知道同花顺是炒股的么?在线开户安全么?
- Build document editor based on slate
- 2016年四川省TI杯电子设计竞赛B题
- What are the top ten securities companies? Is it safe to open a mobile account?
- Using the methods in the repository to solve practical problems
猜你喜欢

Excel operation of manual moving average method and exponential smoothing method for time series prediction

AD - 将修改后的 PCB 封装更新到当前 PCB 中

国际美妆业巨头押注中国

leetcode 715. Range module (hard)

Introduction to the four major FPGA manufacturers abroad
![[redis series] redis learning 16. Redis Dictionary (map) and its core coding structure](/img/d5/db1931596c26090092aaa065103dbb.png)
[redis series] redis learning 16. Redis Dictionary (map) and its core coding structure

JMeter response time and TPS listener tutorial

SQL injection in Pikachu shooting range

Using the methods in the repository to solve practical problems

Redis best practices? If I don't feel excited after reading it, I will lose!!
随机推荐
2022 edition of Beijing 5g industry investment planning and development prospect forecast analysis report
Scala-day06- pattern matching - Generic
International beauty industry giants bet on China
What software is flush? Is online account opening safe?
JMeter response time and TPS listener tutorial
Precautions for opening a securities account is it safe to open an account
Pre knowledge of hash table -- binary search tree
Five strategies and suggestions of member marketing in consumer goods industry
Analysis report on the "fourteenth five year plan" and investment prospect of China's pharmaceutical equipment industry 2022-2028
证券账户可以开通 开户安全吗
How do consumer goods enterprises formulate membership interests?
How can we reach members more effectively?
Scala-day01- companion objects and HelloWorld
This paper introduces the simple operation of realizing linear quadratic moving average of time series prediction that may be used in modeling and excel
Omni channel member link - tmall member link 3: preparation of member operation content
One click deployment CEPH script
Comparison of latest mobile phone processors in 2020 (with mobile phone CPU ladder diagram)
Realize microservice load balancing (ribbon)
I'd like to know what preferential activities are available for stock account opening? Is it safe to open an account online?
Omnichannel membership - tmall membership 2: frequently asked questions