首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >Laravel 5多联器

Laravel 5多联器
EN

Stack Overflow用户
提问于 2017-02-15 19:53:47
回答 2查看 4.8K关注 0票数 2

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

代码语言:javascript
复制
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');
    });

我还有三种型号:

Park.php

代码语言:javascript
复制
public function weathers()
{
    return $this->belongsToMany('App\Weather', 'weather_user_park');
}

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

User.php

代码语言:javascript
复制
public function weathers()
{
    return $this->belongsToMany('App\Weather', 'weather_user_park');
}

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

Weather.php

代码语言:javascript
复制
       public function users()
{
    return $this->belongsToMany('App\User', 'weather_user_park');
}

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

回答 2

Stack Overflow用户

回答已采纳

发布于 2017-02-15 21:44:16

Park.php

代码语言:javascript
复制
public function users()
{
    return $this->belongsToMany('App\User', 'park_user')->withPivot('weather');
}  

User.php

代码语言:javascript
复制
public function parks()
{
    return $this->belongsToMany('App\Park', 'park_user')->withPivot('weather');
}

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

您可以向用户添加如下信息:

代码语言:javascript
复制
$park = App\Park::find(1);
$weather = App\Weather::find($id);
$user->parks()->attach($park->id, ['weather' => $weather->id]); 

删除关系

代码语言:javascript
复制
$user->parks()->detach($park->id);
票数 0
EN

Stack Overflow用户

发布于 2017-02-15 20:13:28

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

代码语言:javascript
复制
$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 (特别是“检索中间表列”部分)

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/42258803

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档