【问题标题】:how can i send multiple data from one select box to save in a pivot table?如何从一个选择框中发送多个数据以保存在数据透视表中?
【发布时间】:2019-08-13 23:44:44
【问题描述】:

我有四个具有多对多关系的模型。 CrewTypePostFlight

Crew 模型中:

public function crews()
    {
        return $this->belongsToMany(Crew::class,'crew_flight_post_type','flight_id','crew_id')
            ->withPivot(['post_id','type_id']);
    }

    public function posts()
    {
        return $this->belongsToMany(Post::class,'crew_flight_post_type','flight_id','post_id')
            ->withPivot(['crew_id','type_id']);
    }

    public function types()
    {
        return $this->belongsToMany(Type::class,'crew_flight_post_type','flight_id','type_id')
            ->withPivot(['crew_id','post_id']);
    }

我用这些列创建了数据透视表crew_flight_post_typecrew_idflight_idtype_idpost_idtotal_flight_time

如何通过create.blade.php 中的一个选择框发送post_idflight_idcrew_idtype_id 查看并保存或更新此数据透视表?

FlightController的in Store方法

 $flight->crews()->attach(request('cap'),['post_id'=>$request->get('?'),'type_id'=>$type_id]);

这是我对Flight 模型的create.blade.php 视图:

<select>
 @foreach($crew as $id => $name)
    <option value="{{ $id }}">{{ $name }}</option>
 @endforeach
</select>

 </div>
@endforeach

【问题讨论】:

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


    【解决方案1】:

    将船员保存到Flight 模型时(根据示例),您需要将Crew 模型作为第一个参数传递,然后您可以将任何枢轴值作为关联数组传递给第二个参数。

    // $flight = Flight::find(?);
    // $crew = Crew::find(?);
    
    // attach a Crew model to a Flight model
    $flight->crews()->attach($crew,[
        'post_id' => ?,
        'type_id' => ?,
        'total_flight_time' => ?,
    ]);
    

    另外,我认为这是一个错字,但您在上面的问题中同时使用了 crew_leg_post_typecrew_flight_post_type,而我猜测它们是同一张表。

    编辑:cmets 中的问题。

    ...在我看来如何发送 post_id 和 type_id。

    您有多种选择。

    1. 您可以直接发送它们,因为您已经有这些可用的,因为它们用于保存航班/机组人员关系。
    return view('your-view',['post_id' => ?, 'type_id' => ?]);
    
    <div>{{ $post_id }}</div> 
    <div>{{ $type_id }}</div>
    
    1. 或者您可以通过关系使用它们。
    return view('your-view',compact('flight'));
    
    @foreach ($flight->crews as $crew)
        <div>{{ $crew->post_id }}</div> 
        <div>{{ $crew->type_id }}</div>
    @endforeach
    
    1. 或者您可以通过在另一个关系上的枢轴来使用它们。
    return view('your-view',compact('flight'));
    
    @foreach ($flight->types as $type)
        <div>{{ $type->pivot->post_id }}</div> 
    @endforeach
    
    @foreach ($flight->posts as $post)
        <div>{{ $post->pivot->type_id }}</div> 
    @endforeach
    

    【讨论】:

    • 你是对的。这是一个错字。和表是 crowd_flight_post_type ,但我怎么能在我看来发送 post_id 和 type_id 。谢谢你的回答
    • 我添加了一些编辑,可能会回答您的第一个问题。抱歉,我不知道您在最后一条评论中要问什么。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-10-20
    • 2011-06-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-03-10
    相关资源
    最近更新 更多