The naming convention norm in Laravel and the relation n+1 problem

Source: Internet
Author: User

User:model; Users: Table name; user_id Key value

Relation:public function Tasks () {return $this->belongstomany (' Task ', ' task_id ');}

Task:model name; tasks: table name; task_id Key value

Relation:public function Ower () {return $this->belongstomany (' User ', ' user_id '),}//Note: By default, if you do not specify a key field, you will use the Owner_ ID as key

$user = User::first ();

$user->tasks ()->attach (2); Action will be performed on relation

Task::where (' title ', ' like ', '% $searchdata% ')->get () Full-text Search

In the Laravel relation operation, if you perform a relation relational table operation on a row with multiple rows of data, the system performance will be severely affected by querying the database multiple times. For example, one possible way is to eager oading.

For example, if you have 10 user in the above relationship, you should display

@foreach ($tasks as $task)

<li><strong>{{$task->owner->name}}</strong> have the following tasks {{$task->title}}</li>

@endforeach

PHP code can be improved a little bit to get the data set after the incoming blade template,

$tasks = Task::with (' owner ')->get (); By the modification of this sentence, laravel access to the database will be reduced to 1 times, not 11 times!! (n+1 problem)

The naming convention norm in Laravel and the relation n+1 problem

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.