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

时间:2013-09-14 12:32:01

标签: php laravel laravel-4

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

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

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

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

1 个答案:

答案 0 :(得分:1)

您只需要创建3种不同的模型。

如果类TypeXTypeY确实使用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';
}
相关问题