fefe
fefe

Reputation: 9055

Laravels Eloquent to store many to many relationship

I have 3 tables

-- networks
    Schema::create('networks', function(Blueprint $table)
        {
            $table->engine = 'InnoDB';

            $table->increments('id');
            $table->string('network');
            $table->string('description',255);
            $table->string('attributes',255);
            $table->timestamps();

        });

and

-- campaigns

 Schema::create('campaigns', function($table) {
                $table->engine = 'InnoDB';
                $table->increments('id');
                $table->string('campaign_title');
                $table->integer('owner')->unsigned();
                $table->string('details');
                $table->timestamps();
            });

            Schema::table('campaigns', function($table) {
                $table->foreign('owner')->references('id')->on('users')->onDelete('cascade');
            });

and -- campaign_networks_relationhsips

Schema::table('campaign_networks_relationhsips', function($table)
    {
        $table->foreign('campaign_id')->references('id')->on('campaigns')->onDelete('cascade');
        $table->foreign('network_id')->references('id')->on('networks')->onDelete('cascade');
    });

On new Campaign creation, in the Form I show available Networks as checkboxes.

User gives a title to the campaign and ads the desired Networks to it and saves.

The question:

has Eloquent a method which would pull this relation directly to the binding tables(campaign_networks_relationhsips) or I have to make 2 queries like saving the campaign and after getting the id of the campaign I use a loop on networks to save this relations in my binding table.

example

created campaign: gives me back id:1 choosed networks 3,4

than loop and save

1-3
1-4 

in campaign_networks_relationhsips

than I try the following

<?php namespace Td\Reports\Controllers\Backend;

use Td\Reports\Campaigns\CampaignsInterface;
use Input,
    Redirect,
    View,
    App,
    Str;
use Illuminate\Support\MessageBag;
class CampaignsController extends ObjectBaseAdminController {

    /**
     * The place to find the views / URL keys for this controller
     * @var string
     */
    protected $view_key = 'admin.campaigns';

    protected $networks;

    /**
     * Construct
     */
    public function __construct(CampaignsInterface $campaigns) {
        $this->model = $campaigns;
        $networks = App::make('Td\Reports\Networks\NetworksInterface');
        $this->networks = $networks->getAll();
        parent::__construct();
    }

   public function postNew() {


        $record = $this->model->getNew(Input::all());
        //$record->campaign_title= Input::get('campaign_title');

        $valid = $this->validateWithInput === true ? $record->isValid(Input::all()) : $record->isValid();

        if (!$valid)
            return Redirect::to('admin/' . $this->new_url)->with('errors', $record->getErrors())->withInput();

        // Run the hydration method that populates anything else that is required / runs any other
        // model interactions and save it.
        $record->save();

        $record->networks()->sync([3,4]);

        return Redirect::to($this->object_url)->with('success', new MessageBag(array('Item Created')));
    }


}

than I have the repository for campaigns

<?php

namespace Td\Reports\Campaigns;

use Td\Reports\Core\EloquentBaseRepository;
use Td\Reports\Abstracts\Traits\NetworkableRepository;
use Datatables,Sentry;

class CampaignsRepository extends EloquentBaseRepository implements CampaignsInterface {


    /**
     * Construct
     * @param Campaigns $campaigns
     */
    public function __construct(Campaigns $campaigns) {
        $this->model = $campaigns;


    public function getAll() {

        if (Sentry::getUser()->hasAnyAccess(['system'])) {
            return $this->model->get();
        } else {
            return $this->model->where('owner', Sentry::getUser()->id)->get();
        }
    }

    public function networks()
    {
        return $this->belongsToMany('Network', 'campaign_networks_relationhsips');
    }

}

Upvotes: 0

Views: 792

Answers (1)

Jarek Tkaczyk
Jarek Tkaczyk

Reputation: 81167

A must read for you: http://laravel.com/docs/eloquent#relationships

From what you wrote I assume you want to save a model and its pivot relations, so here it goes:

// basic example flow in a controller, repo or wherever you like
$campaign = new Campaign;
$campaign->name = Input::get('name');
// assign more campaign attributes
$campaign->save();

$campaign->networks()->sync([3,4]); // 3,4 are existing network rows ids

That's all. For the above to work you need to setup these relationships:

// Campaign model
public function networks()
{
  return $this->belongsToMany('Network', 'campaign_networks_relationhsips');
}

// Network model
public function campaings()
{
  return $this->belongsToMany('Campaign', 'campaign_networks_relationhsips');
}

Upvotes: 2

Related Questions