【问题标题】:I can not access the array that I attached to my pivot table?我无法访问附加到数据透视表的数组?
【发布时间】:2019-12-05 09:25:33
【问题描述】:

我正在使用 StudentsPackages 之间的多对多关系,这会生成 student_package 数据透视表。我附加了一些额外的变量,但我无法在我的视图中访问它们。

这是我的代码

控制器

$student->packages()->attach($request->package_id, ['paid' => '1','transaction_id'=>$transaction_id, 'amount' => $request->amount]);

查看

@foreach ($student->packages as $package)
    <tr>
        <td> {{$package->id}} </td>
        <td> {{$package->name}} </td>
        <td> {{$package->amount}} </td>
        <td> {{$package->no_hours}} </td>
        <td> {{$package->transaction_id}} </td>
        <td> {{$package->paid}} </td>
                                                    
    </tr>
@endforeach

我不能只访问额外的参数。其余的都可以访问。

【问题讨论】:

标签: laravel eloquent many-to-many pivot-table


【解决方案1】:

1)在belongsToMany关系的withPivot()方法中添加你需要的列:

public function packages()
{
    return $this->belongsToMany(Package::class)->withPivot('paid', 'transaction_id', 'amount');
}

2) 然后通过-&gt;pivot 属性访问数据透视列。

@foreach ($student->packages as $package)
    <tr>
        <td> {{$package->id}} </td>
        <td> {{$package->name}} </td>
        <td> {{$package->pivot->amount}} </td>
        <td> {{$package->no_hours}} </td>
        <td> {{$package->pivot->transaction_id}} </td>
        <td> {{$package->pivot->paid}} </td>
    </tr>
@endforeach

【讨论】:

    【解决方案2】:

    您需要使用模型的pivot 属性,如下所述:https://laravel.com/docs/6.x/eloquent-relationships#many-to-many

    例如:

    $user = App\User::find(1);
    
    foreach ($user->roles as $role) {
        echo $role->pivot->created_at;
    }
    

    阅读链接的文档,它为各种用例提供​​了很多详细信息。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2018-01-28
      • 1970-01-01
      • 1970-01-01
      • 2022-06-20
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多