douchi7073 2013-10-14 12:04
浏览 227
已采纳

如何将模型A与Laravel中的模型B或模型C相关联?

I'm using Laravel 4's Eloquent to make three different models: a User model, an Agent model, and a Performer model. Any user can sign up as a normal user, or can pay to become an Agent OR a Performer. Because both Agents and Performers have special profiles, I've created separate tables for both Performers and Agents that will contain their profiles, and just a user "type" in the Users table, which indicates whether they're a normal user, a Performer, or an Agent.

This means that the User model will have a has_one relationship with both Performer and Agent. Because a user will only ever be one of those, I'm wondering if it's possible to have the User model only relate to one of those (or none) depending on what type the user is?

I have a strong feeling that I'm going about this the wrong way. Should I relate the User model to both and just check before I use the relationships (which seemed obvious at first, but not quite the right approach either)? Is there a better way to do this?

EDIT: I specified above that the user might not be either of those but just a normal user, however it seems I was too vague: so, if a user hasn't paid to become either an agent or a performer, they'll just be a normal user. Is the best strategy in that case to just manually fill in "user" for the userable_type column and check to make sure it's not equal to "user" before I do $user->userable?

  • 写回答

1条回答 默认 最新

  • douxunwei8259 2013-10-14 13:11
    关注
    Schema::create('users', function($table)
    {
        $table->increments('id');
        $table->string('username');
        $table->string('imageable_type');  // Will be a string of the class name Agent or Performer
        $table->string('imageable_id');    // Will be the ID of the Agent or Performer.
    });
    
    class User extends Eloquent
    {
        public function imageable()
        {
            return $this->morphTo();
        }
    }
    
    class Agent extends Eloquent
    {
        public function user()
        {
            return $this->morphMany('User', 'imageable');
        }
    }
    
    class Performer extends Eloquent
    {
        public function user()
        {
            return $this->morphMany('User', 'imageable');
        }
    }
    
    $user = User::find(1);
    $type = $user->imageable;  // Type will be either an instance of Agent or Performer
    
    if($type instanceof Agent)
    {
        // Do agent stuff
    } else {
        // Do performer stuff
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 像这种代码要怎么跑起来?
  • ¥15 怎么改成循环输入删除(语言-c语言)
  • ¥15 安卓C读取/dev/fastpipe屏幕像素数据
  • ¥15 pyqt5tools安装失败
  • ¥15 mmdetection
  • ¥15 nginx代理报502的错误
  • ¥100 当AWR1843发送完设置的固定帧后,如何使其再发送第一次的帧
  • ¥15 图示五个参数的模型校正是用什么方法做出来的。如何建立其他模型
  • ¥100 描述一下元器件的基本功能,pcba板的基本原理
  • ¥15 STM32无法向设备写入固件