【问题标题】:Laravel 5 multiple attachLaravel 5 多重附加
【发布时间】:2017-07-04 16:05:03
【问题描述】:

我有来自其他列的 3 个 ID 的表。如何附加2个以上的ID?一世 不知道如何连接三把钥匙。当我尝试做“ $weather->parks()->attach('1')->users()->attach('2');”它不附加park_id。 请帮忙。

Schema::create('weather_user_park', function (Blueprint $table) {
        $table->integer('weather_id')->unsigned();
        $table->integer('park_id')->unsigned();
        $table->integer('user_id')->unsigned();
        $table->foreign('weather_id')->references('id')->on('weathers');
        $table->foreign('park_id')->references('id')->on('parks');
        $table->foreign('user_id')->references('id')->on('users');
    });

我也有 3 个模型:

Park.php

public function weathers()
{
    return $this->belongsToMany('App\Weather', 'weather_user_park');
}

    public function users()
{
    return $this->belongsToMany('App\User', 'weather_user_park');
}

User.php

public function weathers()
{
    return $this->belongsToMany('App\Weather', 'weather_user_park');
}

    public function parks()
{
    return $this->belongsToMany('App\Park', 'weather_user_park');
}

Weather.php

       public function users()
{
    return $this->belongsToMany('App\User', 'weather_user_park');
}

    public function parks()
{
    return $this->belongsToMany('App\Park', 'weather_user_park');
}

【问题讨论】:

  • 您是否尝试过不以这种方式链接方法?并单独调用它?。

标签: laravel relationship foreign-key-relationship


【解决方案1】:

您可以通过在附加方法中添加第二个参数来做到这一点。

$weather->parks()->attach(1, [
    'user_id' => 2,
]);

https://laravel.com/docs/5.4/eloquent-relationships#updating-many-to-many-relationships https://laravel.com/docs/5.4/eloquent-relationships#many-to-many(尤其是“检索中间表列”部分)

【讨论】:

    【解决方案2】:

    Park.php

    public function users()
    {
        return $this->belongsToMany('App\User', 'park_user')->withPivot('weather');
    }  
    

    User.php

    public function parks()
    {
        return $this->belongsToMany('App\Park', 'park_user')->withPivot('weather');
    }
    

    park->users(); 为您提供公园信息

    您可以像这样向用户添加信息:

    $park = App\Park::find(1);
    $weather = App\Weather::find($id);
    $user->parks()->attach($park->id, ['weather' => $weather->id]); 
    

    删除关系

    $user->parks()->detach($park->id);
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2016-06-15
      • 2017-06-08
      • 2018-04-18
      • 2017-11-28
      • 1970-01-01
      • 2017-07-10
      • 2015-06-16
      • 2016-07-22
      相关资源
      最近更新 更多