如何在laravel

时间:2017-11-06 09:05:23

标签: php eloquent laravel-5.3

所以我有一个名为data_storage的模型和另一个模型entity_states

我必须使用data_storageentity_states获取记录,其中entity_state具有data_storage_idstate_id

我如何使用eloquent来实现这一目标?。

或者我必须使用“查询”构建器并使用innerJoin吗?

UPDATE1

我的实际查询

$this->values['new_leads'] = $data_storages->with('actions','states','sla')->where('wf_id',$wfid)->get();

我的data_storage模式

class data_storages extends Model
{
    //
    protected $fillable = ['layout_id','member_id','company_id','team_id','data','status','wf_id'];



    function actions()
    {
        return $this->hasMany('App\Models\ActionDataMaps', 'data_id', 'id' );
    }

    function states()
    {
        return $this->hasOne('App\Models\workflow_states','id','status');
    }

    function sla()
    {
       //Here I have to get those row from entity_states model where , data_storage_id and state_id 
    }
}

由于

3 个答案:

答案 0 :(得分:2)

这是更合理的方法:

class DataStorage extends Model { 
     public states() {
         return $this->belongsToMany(State::class,"entity_states");
     }
}

class State extends Model {
     public storages() {
         return $this->belongsToMany(DataStorage::class,"entity_states");
     }
}

然后你可以通过例如:

来加载相关的模型
$storage = DataStorage::with("states")->first();
$storage->states->first()->column_in_related_state;

或通过州:

$state = State::with("storages")->first();
$state->storages->first()->column_in_related_storage;

如果数据透视表 entity_states中有其他列,那么您可以在关系中引用它们,例如:

public states() {
    return $this->belongsToMany(State::class)->withPivot("pivot_column");
}

答案 1 :(得分:1)

在您的模型data_storage中,您可以定义属性/方法entity_states来获取它们:

class data_storage extends Model
{
    public function entity_states()
    {
        return $this->hasMany('App\entity_states','data_storage_id')->where('state_id ','=',$this->table());
    }
}

然后您可以通过

在实例中访问它们
$entityStatesOfDataStorage = $yourDataStorageInstance->entity_states;

查看此链接: https://laravel.com/docs/5.3/eloquent-relationships

答案 2 :(得分:0)

对于Query Builder,您可以使用:

DB::table('data_storage')
    ->join('entity_states','data_storage.data_storage_id','=','entity_states.state_id')
    ->get();

供参考Laravel Query Builder