Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
632 views
in Technique[技术] by (71.8m points)

laravel - Polymorphic Eloquent relationships with namespaces

I've tried to implement polymorphic relationships. They work perfectly... However, I'm trying to reduce my database size as much as possible so... I've this

Table action
|  id  |  realatable_type  |  relatable_id
|  1   |  LionPeople      |  65
|  2   |  LionCompany     |  13

Obviously I've this

<?php namespace Lion;

class Company extends Eloquent { ... }
class People extends Eloquent { ... }

Is there any way to store only "People" or "Company" assuming that the namespace is always going to be "Lion"?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Since Laravel 4.1, inside your model (in this case Company and People) you can set the protected property $morphClass to whatever you want.

<?php namespace Lion;

class Company extends Eloquent { 

    protected $morphClass = 'Company';
}

Now in your table you can store the type without the namespace:

 |  id  |  realatable_type  |  relatable_id
 |  2   |  Company          |  13

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...