对“BelongsToMany”关系的雄辩查询

时间:2016-01-01 14:27:07

标签: php laravel laravel-5 eloquent

当我想在我的数据库中查询所有状态的特定调度票证时,我会这样做:

el.innerHTML = "New Content"

但是这会抛出一条错误消息,public function test() { $dispatches = Dispatch::where('dispatch_reference', '=', 'dis_548k14s4glnhv5')->get(); foreach($dispatches->states as $state) { var_dump($state); } } 无法识别。我创建的模型是:

调度

states

派遣州

class Dispatch extends Model {

    use EventGenerator;

    protected $table = 'dispatches';
    protected $fillable = ['dispatch_reference', 'incident_reference', 'state'];
    public $timestamps = true;

    // Since the FK exists in this table, the belongsTo() method is used to state that the dispatch model is related to an address.
    // Dispatch __belongs_to__ Incident
    public function incident() {
        return $this->belongsTo('App\Classes\Incident');
    }

    // Dispatch __belongs_to_many__ State
    public function states() {
        return $this->belongsToMany('App\Classes\DispatchState')->withTimestamps();
    }

    public function attachDispatchState($id) {
        $this->states()->attach($id);
        $this->touch();
    }

    // set fields on the eloquent object and save to database
    // raise event that the incident was created.
    public function createDispatch($command) {

        // Get BodyContent from POST Request
        $this->dispatchReference = $command->dispatchReference;
        $this->incidentReference = $command->incidentReference;

        // Create new Dispatch
        $dispatch = Dispatch::create(array(
            'dispatch_reference' => $this->dispatchReference,
            'incident_reference' => $this->incidentReference
        ));
        $dispatchState = DispatchState::where('state', '=', 'processing')->first();
        $dispatch->attachDispatchState($dispatchState->id);

        return $this;
    }

我希望看到所有不同的状态附加到一个调度,因为我使用的透视表到目前为止工作正常。我只是无法查询结果。我的模特中有错误吗?

1 个答案:

答案 0 :(得分:1)

当您致电获取()时,您将获得调度对象的集合。如果您希望只获得一个对象(例如,当调度引用是唯一的)时,请先调用第一个()而不是获取()

$dispatch = Dispatch::where('dispatch_reference', '=', 'dis_548k14s4glnhv5')->first();

但是,如果调度参考不是唯一的,那么您需要首先遍历调度的集合,然后再通过其相关状态:

$dispatches = Dispatch::where('dispatch_reference', '=', 'dis_548k14s4glnhv5')->get();
foreach($dispatches as $dispatch) {
  foreach ($dispatch->states as $state) {
    var_dump($state);
  }
}