Laravel Eloquent存储了许多关系

时间:2014-09-12 17:36:11

标签: laravel-4 save many-to-many eloquent

我有3张桌子

-- 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();

        });

-- 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');
            });

和      - 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');
    });

在新广告系列创建时,在表单I中显示可用网络作为复选框。

用户为广告系列提供标题,并向其投放所需的网络并进行广告保存。

问题:

有一个Eloquent方法可以直接将这种关系拉到绑定表(campaign_networks_relationhsips),或者我必须进行2次查询,比如保存广告系列,在获得广告系列的ID之后,我会在网络上使用循环来保存这种关系。我的约束表。

示例

创建广告系列:给我回ID:1 选择网络3,4

比循环并保存

1-3
1-4 

in campaign_networks_relationhsips

比我尝试以下

<?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')));
    }


}

比我拥有广告系列

<?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');
    }

}

1 个答案:

答案 0 :(得分:2)

必须为您阅读:http://laravel.com/docs/eloquent#relationships

根据你所写的内容,我假设你想保存一个模型及其枢轴关系,所以在这里:

// 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

这就是全部。要使上述工作正常,您需要设置这些关系:

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

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