[英]Laravel hasOne through a pivot table
所以我有2個模型,User & Profile,關系設置如下:
/**
* User belongs to many Profile
*
* @return \Illuminate\Database\Eloquent\Relations\belongsToMany
*/
public function profiles()
{
return $this->belongsToMany('App\Models\Profile', 'user_profiles');
}
我有 3 個表、用戶、配置文件和 user_profiles(數據透視表)
我的用戶表中有一個名為active_profile
的列,其中填充了配置文件 ID。
我如何建立關系,以便我可以調用以下內容:
$user->active_profile
以便它將返回active_profile中設置的id的所有配置文件信息?
在 Laravel 5.8 上,因為我想在預加載中使用它,所以我使用了這個包: https : //github.com/staudenmeir/eloquent-has-many-deep
這是我的場景
一個用戶可以在許多照片上被標記,一張照片可以有許多用戶被標記。 我想建立一個關系來獲取用戶被標記的最新照片。
我認為我的場景也可以應用於任何多對多關系
我做了樞軸模型UserPhoto
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Relations\Pivot;
class UserPhoto extends Pivot
{
public function user()
{
return $this->belongsTo(User::class);
}
public function photo()
{
return $this->belongsTo(Photo::class);
}
}
然后在我的User模型上使用staudenmeir的包:
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Model;
use Staudenmeir\EloquentHasManyDeep\HasRelationships;
class User extends Model
{
use HasRelationships;
public function photos()
{
return $this->belongsToMany(Photo::class);
}
public function latestPhoto()
{
return $this->hasOneDeep(Photo::class, [UserPhoto::class])
->latest();
}
}
然后我可以輕松地做這樣的事情:
User::with('latestPhoto')->get()
和$user->latestPhoto
編輯:在另一個問題中,有人在不使用包的情況下問了同樣的問題。 我還提供了一個可以產生相同結果的答案。
但是在深入挖掘之后,從這兩個答案中,您可能會避免 n+1 查詢,您仍然會從請求的用戶那里獲取所有照片。 我認為不可能避免一種或另一種方法。 不過,緩存可能是一個答案。
我可能是錯的,但為什么不使用belongsTo
關系呢?
public function active_profile()
{
return $this->belongsTo('App\Models\Profile', 'active_profile');
}
希望這可以幫助!
您可以將方法添加到您的User
模型中,如下所示:
public function active_profile ()
{
return $this->profiles()
->find($this->active_profile);
}
然后你可以調用該方法為 $user->active_profile();
您可以在數據透視表中添加額外的字段,例如active = enum(y, n)
,然后設置unique key (user_id, active)
然后在用戶模型中使用wherePivot
方法:
public function profiles()
{
return $this->belongsToMany('App\Models\Profile', 'user_profiles');
}
public function activeProfile()
{
return $this->belongsToMany('App\Models\Profile', 'user_profiles')->wherePivot('active', 'y');
}
雖然它需要數據庫重構。
您應該能夠使用find
獲取資源
$user->profiles()->find($user->active_profile);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.