doubi6898 2018-09-06 06:17
浏览 259

如何动态设置Laravel Model表/集合?

I am using GitHub - jenssegers/laravel-mongodb: A MongoDB based Eloquent model and Query builder for Laravel; In my Laravel project I created DB model that sets Model table name dynamically (in Mongodb case collection) .

use Jenssegers\Mongodb\Eloquent\Model as Eloquent;

class DbData extends Model
    {   
        protected   $collection = 'default_collection';
        function __construct($collection)
            {
                $this->collection = $collection;
            }
    }

This works when I am creating new DbData object, for data insert:

$data = new DbData('dynamic_collection_name');
$data->variable = 'Test';
$data->save();

But this solution is not enough of I want to use this DbData model for querying data from my database. What I want to achieve is to add possibility to pass variable for DbModel, for instance something like this:

$data = DbData::setCollection('dynamic_collection_name');
$data->get();
  • 写回答

1条回答 默认 最新

  • douxuanma4357 2018-09-06 07:30
    关注

    You could perhaps do something like this on your class.

    use Jenssegers\Mongodb\Eloquent\Model as Eloquent;
    
    class DbData extends Model
    {   
        protected   $collection = 'default_collection';
    
        public function __construct($collection)
        {
            $this->collection = $collection;
        }
    
        public static function setCollection($collection)
        {
            return new self($collection);
        }
    }
    

    This will allow you to call DbData::setCollection('collection_name') and the collection name will only be set for that specific instance.

    评论

报告相同问题?

悬赏问题

  • ¥15 关于#c语言#的问题:我现在在做一个墨水屏设计,2.9英寸的小屏怎么换4.2英寸大屏
  • ¥15 模糊pid与pid仿真结果几乎一样
  • ¥15 java的GUI的运用
  • ¥15 Web.config连不上数据库
  • ¥15 我想付费需要AKM公司DSP开发资料及相关开发。
  • ¥15 怎么配置广告联盟瀑布流
  • ¥15 Rstudio 保存代码闪退
  • ¥20 win系统的PYQT程序生成的数据如何放入云服务器阿里云window版?
  • ¥50 invest生境质量模块
  • ¥15 nhanes加权logistic回归,svyglm函数