【问题标题】:Laravel 5 - Many to many relations - Getting the pivot dataLaravel 5 - 多对多关系 - 获取数据透视表
【发布时间】:2015-07-18 16:35:22
【问题描述】:

您好,我有以下数据库结构

User 有两种类型的用户ArtistFans 并有两个表artistsfans 来存储唯一数据

用户模型

public function artist()
    {
            return $this->hasOne('App\Artist');
    }
public function fans()
    {
        return $this->hasOne('App\Fan');
    }

艺术家会有多个粉丝,所以我创建了一个 pivot 表来存储关系

艺人模特

public function fans() {
        return $this->belongsToMany('App\Fan');
    }

粉丝模型

public function artist() {
        return $this->belongsToMany('App\Artist');
    }

数据透视表架构

Schema::create('artist_fan', function(Blueprint $table)
        {
            $table->increments('id');
            $table->integer('artist_id')->unsigned();
            $table->integer('fan_id')->unsigned();
            //
        });

我使用了以下代码,但结果是一个空集合

$user = auth()->user();
dd($user->artist->fans);

输出

Collection {#263 ▼
  #items: []
}

请帮我找回当前登录艺术家的粉丝。还对数据透视表进行 CRUD 操作。

【问题讨论】:

    标签: php laravel eloquent laravel-5


    【解决方案1】:

    你可以试试这个:

    $artists = \App\Artist::has('fans') // Artists who has fans
                          ->with('fans') // load fans
                          ->where('user_id', auth()->user()->id) // Where artist.user_id = logged in user id
                          ->get(); // Get all artists
    
    if($artists->count())
    {
        $fans = $artists->fans; // Get fans
    }
    

    【讨论】:

    • if($artists->count() > 0) { $fans = $artists[0]->fans; }
    • 哎呀!我弄错了,应该是if($artists->count()) :-)
    猜你喜欢
    • 2020-07-03
    • 1970-01-01
    • 2015-02-10
    • 1970-01-01
    • 2023-02-05
    • 2018-09-15
    • 1970-01-01
    • 2018-09-23
    相关资源
    最近更新 更多