mardi 23 février 2021

Polymorphic many to many relation in laravel

First time I used polymorphic many to many relation in LARAVEL 5.1 but somehow it doesn't work I attach my code can you find out what I do wrong?

Tables

users table

 id | name | email
 -------------------------
 1 | john | john@gmail.com
 --------------------------
 2 | adam | adam@gmail.com

companies table

id | name | email
-----------------
 1 | tesla | tesla@gmail.com

calendar_subscriptions table

id | user_id | resourceable_type | resourceable_id
--------------------------------------------------
 1 | 1       | App\Models\User   | 2
--------------------------------------------------
 2 | 1       | App\Models\Company | 1

CalendarSubscription Model

 class CalendarSubscription extends Model
 {
   protected $table = 'calendar_subscriptions';


   public function resourceable()
   
   {  
     return $this->morphTo();
   }

 }

User Model

class User extends Model {

 public function calendarSubscription()
 {
    return $this->morphMany('App\Models\CalendarSubscription','resourceable');
 }
}

Tried

  User::with('calendarSubscription')->where('id', '=', Auth::user()->id)->get();

Problem It does not return these name adam and tesla

Want below data in collection form

 id | name | email
 -------------------------
 1 | john | john@gmail.com
 --------------------------
 2 | adam | adam@gmail.com
 --------------------------
 1 | tesla | tesla@gmail.com

First Fetch all the details from calendar_subscriptions where user_id = 1 then get the name of company and user.

I know project structure is wrong. I could not change anything and must follow this structure



via Chebli Mohamed

Aucun commentaire:

Enregistrer un commentaire