简体   繁体   中英

Laravel Polymorphic Relationships

What is the best method to handle an instance where there is no record for the polymorphic object.

   user_type A table ( user_id , username )

   user_type B table (user_id , username )

   event table (event_id, user_id, user_type )

Sample Data

A_table user_id , username 1 , sam 2 , john

B_table user_id, username 1, Don 2, Mike

Event_table event_id, user_id, user_type 1,1,A // Record 1 2,2,B // Record 2 1,5,A // Record 3

Consider the following pseudo code :
Event instance ->user->username

1) Running the above for Record 1 Should result in "Sam" 2) Running the above for Record 2 Should result in "Mike"

Imagine a 3rd case :

Where as "Event instance ->user" results in NULL.

How do we best tackle a situation like this apart from having to always check if the Object is null or not before every instance we use it.

The best method to go around this was to do a simple :

if ( ! $this->polymorfphic_object_method)
{
  // skip now
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM