Laravel 5 - 多对多关系 - 获取数据透视数据

时间:2015-07-18 16:35:22

标签: php laravel eloquent laravel-5

您好我有以下数据库结构

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操作。

1 个答案:

答案 0 :(得分:2)

你可以试试这个:

$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
}