我有3个表:
Schema::create('users', function (Blueprint $table) {
$table->id();
$table->string('name');
$table->string('email')->unique();
$table->timestamp('email_verified_at')->nullable();
$table->string('password');
$table->rememberToken();
$table->timestamps();
});
Schema::create('cities', function (Blueprint $table) {
$table->integer('id')->primary();
$table->string('name',100);
$table->string('state',50)->nullable();
$table->string('country',10);
$table->float('lot');
$table->float('lat');
});
Schema::create('followed_cities', function (Blueprint $table) {
$table->id();
$table->integer('user_id');
$table->integer('city_id');
});
我在User类中建立了这个关系:
public function cities()
{
return $this->hasManyThrough(City::class,FollowedCity::class);
}
我试着把这段代码放入控制器,但它不起作用
$id=Auth::user()->id;
$followedCities = User::with('cities')->findOrFail($id);
我正在尝试获取该用户关注的每个城市的详细信息。有人能帮帮我吗?
你需要使用多对多关系
inUser.php
public function cities()
{
return $this->belongsToMany(City::class , 'followed_cities');
}