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 Vue3 大型图片数据拖动排序
  • ¥15 划分vlan后不通了
  • ¥15 GDI处理通道视频时总是带有白色锯齿
  • ¥20 用雷电模拟器安装百达屋apk一直闪退
  • ¥15 算能科技20240506咨询(拒绝大模型回答)
  • ¥15 自适应 AR 模型 参数估计Matlab程序
  • ¥100 角动量包络面如何用MATLAB绘制
  • ¥15 merge函数占用内存过大
  • ¥15 使用EMD去噪处理RML2016数据集时候的原理
  • ¥15 神经网络预测均方误差很小 但是图像上看着差别太大