如何为每个用户类型创建单独的模型


How to create separate model for each user type

>我有处理用户表的基本用户模型,我有两种类型的用户,每种类型都有不同的属性,并从不同的数据库中读取这些属性。

  User: name, email, type (x,y)
  type_x: gender, age
  type_y: color, location

所以我有user表,type_x表和type_y表。

如何创建三个不同的模型:User、Typex 和 Typey,以便能够以不同的方式检索每个模型的数据并处理不同的表?

您所需要的只是创建 3 个不同的模型。

如果类TypeX并且TypeY使用类User的方法,请扩展该类。如果不需要,只需扩展Eloqeunt类。

你写道,每种类型都会使用不同的数据库 - 你必须指定不同的连接。好吧,只需添加$connection属性。Laravel使用命名连接,因此请使用文件中指定的连接名称app/config/database.php因此。

<?php
class User extends Eloquent
{
    // this model loads data user table from default connection
    protected $table = 'user';
    // other methods...
}
class TypeX extends User
{
    // this model loads data user table
    protected $table = 'user';  
    // ... but from different DB connection
    protected $connection = 'connection1';
}
class TypeY extends User
{
    // this model loads data user table
    protected $table = 'user';
    // ... but from different DB connection
    protected $connection = 'connection2';
}