Laravel Model访问其自身实例的值

时间:2016-02-08 04:51:47

标签: laravel laravel-5.2

我有一个模型和模型,其自身可以链接到多个其他数据库,但一次只能链接一个。

而不是为所有可能的数据库提供雄辩的方法;它可以有一个将使用自我实例中的变量来选择数据库并返回它。

它将节省大量工作,因为返回每个工作并测试是否有任何结果是麻烦的。

<?php

namespace App;

use Illuminate\Database\Eloquent\Model;

class Feature extends Model
{
/**
 * The database table used by the model.
 *
 * @var string
 */
protected $table = 'companies';

/**
 * The attributes that are mass assignable.
 *
 * @var array
 */
protected $fillable = [
    'name',
];

    /**
     * The attributes excluded from the model's JSON form.
     *
     * @var array
     */
    protected $hidden = [
        'db_name',
        'enabled',
    ];


    /**
     * Uses the its own database name to determine which input to return.
     */
    public function inputs() {
       // if this->hidden->db_name == 'input type 1'
           // return $this->HasMany(InputType1::class);
       .... and so on
    } // end function inputs

}

2 个答案:

答案 0 :(得分:0)

这绝对是一种奇怪的行为,但我认为你可以达到你想要的目标:

//in your model
public function inputs()
{
    switch ($this->attributes['db_name']) {
        case : 'input type 1':
        return $this->hasMany(InputType1::class);
        case : //some other database name
        return //another relation
   }
}

答案 1 :(得分:0)

扩大shempognon的答案,我实际上需要工作的是

switch($this->db_name) {
     case 'Input_Timesheet':
      return $this->hasMany(Input_type1::class);
}