Laravel - 节省多种模型/关系

I have 3 models: User, Campagin, CampaginType

  • User has many Campagin

  • Campagin belongs to CampaginType

(User does not related with CampaginType)

When I save a campaign (contains user_id and campaign_type_id field), how can I save 2 fields with a single command.

I try like: $user->campaigns()->campaignType($campaignType)->create($campaignInfo);

But It not work! :(

public function store(Request $request)
{
    Campaign::create($request->all());
    $campaign = Campaign::where('unique_field', '=', $request->uniquefield)->first();
    $campaign->users()->attach($request->user_id);
    $campaign->campaign_type()->attach($request->campaign_type_id);

    return redirect('your_destination_view');
}

Note

uniquefield is something that is unique to your campaign database table. You should also modify the models by adding the respective methods to make the eloquent relationship.