Laravel 4:一个模型可以服务几个DB表吗? [英] Laravel 4: can one model serve several DB tables?

查看:92
本文介绍了Laravel 4:一个模型可以服务几个DB表吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在我的应用程序中,我有几个mysql表:多伦多,温哥华,蒙特利尔等...我正在使用DB类与他们一起工作,例如。

  $ data = DB :: select('select * from toronto where id =?',array($ id)); 

我想做的是开始使用口才。我是Laravel的新人,只是想知道是否有可能有一个模型工作与几个表,smth像:

  class City扩展Eloquent {
protected $ table_a ='toronto';
protected $ table_b ='vancouver';
protected $ table_c ='montreal';
}


解决方案

。有很多方法,这里有一个:



创建一个城市模型,在其构造函数中要求一个表名:



$ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $


public function __construct($ city,array $ attributes = :: __构造($属性);

$ this-> table = $ city;
}

}

要使用它,你会有使用表名实例化你的课程:

  $ toronto = new City('toronto'); 

然后你可以做任何你想要的东西:

  var_dump($ toronto-> where('id',701057) - > get()); 


In my application I have several mysql tables: Toronto, Vancouver, Montreal, etc... and I am using the DB-class to work with them, eg.

$data = DB::select('select * from toronto where id = ?', array($id));

What I want to do is to start using Eloquent. I am new to Laravel and was just wondering if its possible to have one model work with several tables, smth like:

class City extends Eloquent {
      protected $table_a = 'toronto';
      protected $table_b = 'vancouver';
      protected $table_c = 'montreal';
}

解决方案

It cannot, but you can. There are many ways, here's one:

Create your a City model that asks for a table name in its constructor:

class City extends Eloquent {

    public function __construct($city, array $attributes = array())
    {
        parent::__construct($attributes);

        $this->table = $city;
    }

}

To use it you'll have to instantiate your class using the table name:

$toronto = new City('toronto');

Then you can do anything you want with it:

var_dump( $toronto->where('id',701057)->get() );

这篇关于Laravel 4:一个模型可以服务几个DB表吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆