Laravel Eloquent relationships Shorthand table

Source: Internet
Author: User
Eloquent relationships Shorthand table there is a big pit in the Model association: When the Belongsto is reversed, the foreign key is automatically searched by the method name plus _id. In addition, the association is based on the model name plus _id as the foreign key.

Type Define Inverse Remark
One to one HasOne Belongsto Withdefault ()

Define default foreign key→based on the model name

Inverse default foreign key→name of the relationship method and suffixing the method name with _id
One to many Hasmany Belongsto Define default foreign key→based on the model name

Inverse default foreign key→name of the relationship method and suffixing the method name with _id
Many to many Belongstomany Belongstomany Requires Intermediate table.

Withpivot (' Column1 ', ' column2 ');

Withtimestamps ();

As (' subscription ') →withtimestamps ();

Wherepivot (' approved ', 1)

Wherepivotin (' priority ', [1, 2]);

using (' App\userrole ');
has many Through Hasmanythrough Hasmanythrough (' App\post ', ' app\user ');
Polymorphic Morphmany Morphto Morphmany (' app\comment ', ' commentable ')

$comment = App\comment::find (1);
$commentable = $comment →commentable;
↑will return either a Post or Video instance, depending on which type of model owns the comment

Morphmap
Many to many polymorphic Morphtomany Morphedbymany Morphtomany (' App\tag ', ' taggable ');

Morphedbymany (' App\post ', ' taggable ');

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.