简体   繁体   English

如何从数据透视表中获取额外的字段-Laravel

[英]How to get extra fields from pivot table - laravel

I have create a Pivot model and table for laravel and added extra field to the pivot model. 我为laravel创建了数据透视模型和表格,并向数据透视模型添加了额外的字段。 But the extra field is not displaying when calling pivot data. 但是,在调用数据透视表数据时,不会显示额外的字段。

I have a Customer model and Tag model. 我有一个客户模型和标签模型。 And a pivot called CustomerTag Created a User with tags and added extra fiend to pivot table using 名为CustomerTag的数据透视表使用标签创建了一个用户,并使用

$user = User::create([
     'name' => 'User 1'
]);
$tag = 1;

$user->tags()->attach($tag, ['priority' => 1]);

But when I calling result 但是当我打电话给结果时

$use = User::find($id);
dd($user->tags->pivot);

The result doesn't have priority field. 结果没有priority字段。

You have to call withPivot function when establishing the association on User model: 在用户模型上建立关联时,必须调用withPivot函数:

public function tags()
{
    return $this->belongsToMany(Tag::class, 'customer_tag', 'user_id', 'tag_id')
                ->withPivot('priority');
}

and then call it when getting the result: 然后在得到结果时调用它:

$tags = $user->tags;
foreach ($tags as $tag) {
    $priority = $tag->pivot->priority;
}

In many to many relationship tags have multiple results 在多对多关系标签中有多个结果

try 尝试

dd($user->tags[0]->pivot);

or use loop 或使用循环

 foreach ($user->tags as $tag){
    dd($tag->pivot);
 }

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

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