Laravel relational model of multiple pairs

Source: Internet
Author: User
Tags php class
Larav Pivot table and multi-pair relationshipBig | In

Today we are talking about a feature that is laravel, but may be a bit difficult to understand at first. The Pivot table is an intermediate table of relationships between two "primary tables." Pivot Table Instance

In official documents, they use user-role (user-role) relationships as examples, and users may belong to multiple roles, and vice versa. To make our understanding clearer, here's another example: stores (shops ) and goods (products).

We assume that a merchant has multiple stores all over the country and that there are a variety of goods that they need to store which goods are sold by which store. This is a very good example of a many-to-many relationship: a product can belong to more than one store, and a store will have a lot of merchandise.

So here's a potential database structure:

Shops

–id

–name

Products

–id

–name

Product_shop

–product_id

–shop_id

The last table in the list   product_shop   is the table that is called "pivot" in the title. Here are a few things to note: The pivot table name should contain the singular form of two table names, separated by underscores, and sorted alphabetically, so we end up with a   product_shop     shop_product  . You can use the Artisan make:migration command to create pivot tables, or through Jeffrey Way extension packs Laravel generators Extended 5 artisan: Pivot command. Pivot table fields: By default, you only need to include two fields – corresponding to the foreign keys of two tables, here is   product_id   and   shop_id  . You can also add multiple fields if you want, and we'll discuss them later. Multi-pair relationship model: Belongstomany

We already have database tables and migrations, so let's create a model for them now. The main point here is to assign a many-to-many relationship that can be defined in any one of the main table models. Select 1:app/shop. PHP class Shop extends Model
{
/**
* The products which belong to the shop.
*/
Public Function Products ()
{
return $this->belongstomany (' app\products ');
}
Select 2:app/product.php Class Product extends Model
{
/**
* The shops that belong to the product.
*/
Public Function shops ()
{
return $this->belongstomany (' app\shop ');
}
}

In fact, you can do it all, mainly by looking at how you use the relationship in your code-whether you need to $shop->products or $product->shops, or both.

In this statement, Laravel assumes that the pivot table name complies with the rules mentioned above, namely Product_shop. If not, you can provide a second parameter: Public function products ()
{
return $this->belongstomany (' app\products ', ' products_shops ');
}

In addition, you can specify the names of the fields in the pivot table if they are not used for product_id and shop_id. You only need to add two parameters: The first is the field of the current model, and the other is the field that needs to be associated with the model: public Function products ()
{
return $this->belongstomany (' app\products ', ' products_shops ',
' shops_id ', ' products_id ');
}

One of the main benefits here is that you don't need to create a separate productshop model. Multi-many-to-many Relationship management: Attach-detach-sync

Now that the data tables and models are ready, the question now is if we save the data using only two models instead of the third intermediate model. Look at the following points.

For example, we need to add a product (product) to the current store (shop>) instance, and we can use the Attach () method in the relational function: $shop = Shop::find ($shop _id);
$shop->products ()->attach ($product _id);

The result is that we add a new column to the product_shop table, with values of $product _id and $shop _id respectively.

Similarly, we can also dismiss ( detach ) A relationship, assuming we remove a product from the store: $shop->products ()->detach ($product _id);

Or further, delete all the items in a particular store, just call the method and do not pass the parameter: $shop->products ()->detach ();

You can attach and detach relationships by passing array parameters: $shop->products ()->attach ([123, 456, 789]);
$shop->products ()->detach ([321, 654, 987]);

Another function that is not useful is to update the entire pivot table. A common example is: in the management panel, there is a multiple-selection box in the store below a product, and when performing an update operation, you need to check all the stores, remove the nonexistent ones from the new multiple-selection array, and add or update them. A headache thing.

But now it's not, there's a method called Sync () that takes an array parameter and then automatically performs all the synchronization work. $product->shops ()->sync ([1, 2, 3]);

The result is that, regardless of the value in the previous Product_shop table, after calling the method, there will be only three rows of shop_id 1, 2, 3. Add extra columns to the pivot table

As I mentioned above, you probably want to add extra fields to the pivot table. In our case, it is necessary to save the quantity and timestamp of the goods in a particular store. We can use migration to add fields as usual, but we also need to make some modifications to the model: public Function products ()
{
return $this->belongstomany (' app\products ')
->withpivot (' Products_amount ', ' price ')
->withtimestamps ();
}

As you can see, we can add a timestamp using a simple Withtimestamps () method and add additional fields by adding parameters to the Withpivot () method.

Now we can use these values in the loop of the code, with a property called pivot: foreach ($shop->products as $product)
{
Echo $product->pivot->price;
}

Basically,->pivot represents the pivot middle table and accesses the fields we mentioned, such as Created_at.

Now, how to invoke the Attach () method is to add these values. The method accepts another array parameter, and you can add all the additional fields you need to it. $shop->products ()->attach (1, [' Products_amount ' =>, ' price ' => 49.99]); Summarize

Therefore, the pivot table can be very convenient to deal with the many-to-many relationships in eloquent, it does not need to create a separate model for this intermediate table. I hope this article will be of some help to you.

From: laraveldaily.com

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.