简体   繁体   English

laravel枢轴返回null

[英]laravel pivot returning null

I am working on a site which using laravel framework. 我正在使用laravel框架的网站上工作。 I have two tables with many to many relationship, the table are training and budget , and also a join table budget_training . 我有两个具有多对多关系的表,该表是trainingbudget ,还有一个budget_trainingbudget_training

in both training and budget model, i define the relation like this; 在培训和预算模型中,我都这样定义关系:

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

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

why in the view $training->pivot is returning null? 为什么在视图中$training->pivot返回null? what is wrong with the code? 代码有什么问题?

full code 完整的代码

// 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');
    }

}

code to insert the data 插入数据的代码

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 containing this, $trainings from its controller 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

here is the index method. 这是索引方法。

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

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

You can't access the pivot object of your models because they haven't been joined over the pivot table. 您无法访问模型的枢轴对象,因为它们尚未通过枢轴表进行联接。

In your code you just select all the training rows from the db without any use of the pivot table. 在您的代码中,您只需从数据库中选择所有训练行,而无需使用数据透视表。 So you have no connection to Budget and therefore no pivot object. 因此,您与Budget没有任何关系,因此也没有枢纽对象。

What would work instead would be getting all trainings from one budget like that 可行的是从这样一个预算中获得所有培训

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

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

Or what you probably want is this: 或者您可能想要的是:

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

If you do this make sure you use 如果这样做,请确保使用

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

So it doesn't have to query the db every time you call ->budget on a training 因此,不必每次调用->budget培训->budget时都查询数据库

If you want to access pivot data, you can do it this way, for example: 如果要访问数据透视表,可以使用这种方式,例如:

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

So you don't access pivot data on model, but on relation, in this case not: 因此,您不在模型上访问数据透视表,但在关系上,在这种情况下,您不能访问:

$training->pivot->amount

but

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

(assuming $i is loop index) (假设$i是循环索引)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM