laravel pivot返回null

时间:2014-11-20 11:36:52

标签: php laravel eloquent

我正在使用laravel框架的网站上工作。我有两个表有多对多关系的表,表是trainingbudget,还有一个联接表budget_training

在培训和预算模型中,我定义了这样的关系;

// in Training model
public function budget(){
   return $this->belongsToMany('Budget')->withPivot('amount');
} 

// in Budget model
public function training(){
   return $this->belongsToMany('Training')->withPivot('amount');
}

为什么在视图$training->pivot中返回null?代码出了什么问题?

完整代码

// Budget.php
class Budget extends \Eloquent {

    // Add your validation rules here
    public static $rules = [
        // 'title' => 'required'
    ];

    // Don't forget to fill this array
    protected $fillable = ['name'];

    // public function training(){
    //  return $this->belongsToMany('Training')->withPivot('amount');
    // }

}

// Training.php
class Training extends \Eloquent {

    // Add your validation rules here
    public static $rules = [
        // 'title' => 'required'
    ];

    // Don't forget to fill this array
    protected $fillable = [
        'name',
        'city',
        'province',
        'budget_year',
        's_date',
        'e_date'
    ];

    public function material(){
        return $this->hasMany('Material');
    }

    public function budget(){
        return $this->belongsToMany('Budget')->withPivot('amount');
    }

}

插入数据的代码

public function postStore(){
    $validator = Validator::make($data = Input::all(), Training::$rules);

    if ($validator->fails())
    {
        return Redirect::back()->withErrors($validator)->withInput();
    }

    $training = Training::create($data);

    foreach(Input::get('budgets') as $k=>$v){
        preg_match('/(\d)/', $k, $budget_id);
        if(count($budget_id) > 0){
            $budget_training = new BudgetTraining;
            $budget_training->budget_id = $budget_id[0];
            $budget_training->training_id = $training->id;
            $budget_training->amount = str_replace(',', '', $v);
            $budget_training->save();
        }
    }

    return Redirect::to('trainings/index');
}

index.blade.php包含来自其控制器的$trainings

@foreach($trainings as $training)
            {{ var_dump($training->pivot) }}
            <tr>
                <td>{{ $training->name }}</td>
                <td>{{ $training->budget_year }}</td>
                <td>{{ $training->city }}, {{ $training->province }}</td>
                <td>{{ $training->s_date }}</td>
                <td>{{ $training->e_date }}</td>
                <td>
                    <a href="{{ url('trainings/edit/'.$training->id) }}" class="btn btn-info"><i class="fa fa-edit"></i></a>
                    <a href="{{ url('trainings/destroy/'.$training->id) }}" class="btn btn-danger"><i class="fa fa-trash-o"></i></a>
                </td>
            </tr>
            @endforeach

这是索引方法。

public function getIndex(){
    $trainings = Training::all();

    return View::make('trainings.index', compact('trainings'));
}

2 个答案:

答案 0 :(得分:2)

您无法访问模型的数据透视对象,因为它们尚未通过数据透视表加入。

在您的代码中,您只需从数据库中选择所有训练行,而无需使用数据透视表。因此,您与Budget没有任何关联,因此没有枢轴对象。

相反,将会从一个预算中获得所有培训

$trainings = Budget::find(1)->training;

foreach($trainings as $training){
    var_dump($training->pivot);
}

或者您可能想要的是:

foreach($trainings as $training){
    $budgets = $training->budget;
    foreach($budgets as $budget){
        var_dump($budget->pivot);
    }
}

如果这样做,请确保使用

$trainings = Training::with('budget')->get();

因此,每次在培训中致电->budget时都不必查询数据库

答案 1 :(得分:1)

如果要访问数据透视数据,可以这样做,例如:

$training = Training->with('budget')->find(1);
echo $training->name;
foreach ($training->budget as $b) {
  echo $b->name.' '.$b->pivot->amount."<br />"
}

因此,您不能访问模型上的数据透视数据,但在关系上,在这种情况下不是:

$training->pivot->amount

$training->budget[$i]->pivot->amount

(假设$i是循环索引)