【问题标题】:Laravels Eloquent to store many to many relationshipLaravel Eloquent 存储多对多关系
【发布时间】:2014-09-12 17:36:10
【问题描述】:

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

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

用户为广告系列命名,并向其投放所需的网络并保存。

问题:

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

}

【问题讨论】:

  • 改写你的问题,你什么都没说
  • 我重新分解了我尽力而为的问题

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


【解决方案1】:

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

【讨论】:

  • 我尝试使用您在我的存储库中提供的,但我没有开始工作我收到调用未定义的方法 Illuminate\Database\Query\Builder::sync()。我做了什么我添加了 public function networks() { return $this->belongsToMany('Network', 'campaign_networks_relationhsips'); } 到我的 Campaign 存储库等另一个到我的网络存储库,而不是从 Controller 我尝试保存数据,但出现上述错误
  • 没有代码我帮不了你。该错误表明您正在尝试在Builder 对象上调用sync,而它是BelongsToMany 方法。
  • 我更新了代码也许你可以指导我,那将不胜感激
  • 我想你的基础 repo 类上有一个神奇的__call,它将方法调用转发到底层 Eloquent 模型,这就是错误发生的地方(?)。无论如何不要在回购中定义关系,而是在模型上。
  • 是的,有一个基础仓库和模型,我将上面的代码放在扩展我的基础模型的类中(Campaigns.php*,CampaignsInterface.php,CampaignsRepository.php),但仍然是错误类'找不到网络,但无论如何应该从哪里加载网络作为类
猜你喜欢
  • 2019-06-13
  • 2017-07-17
  • 2019-03-26
  • 1970-01-01
  • 2013-02-09
  • 2013-05-27
  • 2013-05-15
  • 2016-11-03
  • 2014-09-27
相关资源
最近更新 更多