fix:optimize portfolio_users query

This commit is contained in:
hackerESQ
2024-10-25 22:06:46 -05:00
parent 89c1892013
commit 57495d36d8
3 changed files with 16 additions and 6 deletions
+6 -1
View File
@@ -107,7 +107,12 @@ class Portfolio extends Model
public function getOwnerAttribute() public function getOwnerAttribute()
{ {
return $this->users()->firstWhere('owner', 1); if (!$this->relationLoaded('user')) {
$this->load('users');
}
return $this->users->where('pivot.owner', true)->first();
} }
public static function ensurePortfolioHasOwner(self $portfolio) public static function ensurePortfolioHasOwner(self $portfolio)
+5 -1
View File
@@ -25,7 +25,11 @@
<x-ib-toolbar :title="$portfolio->title"> <x-ib-toolbar :title="$portfolio->title">
@if($portfolio->wishlist) @if($portfolio->wishlist)
<x-badge value="{{ __('Wishlist') }}" class="badge-secondary mr-3" /> <x-badge value="{{ __('Wishlist') }}" title="{{ __('Wishlist') }}" class="badge-secondary mr-3" />
@endif
@if(auth()->user()->id !== $portfolio->owner_id)
<x-badge value="{{ $portfolio->owner->name }}" title="{{ __('Owner').': '.$portfolio->owner->name }}" class="badge-secondary badge-outline mr-3" />
@endif @endif
@can('fullAccess', $portfolio) @can('fullAccess', $portfolio)
+5 -4
View File
@@ -14,6 +14,7 @@ class PortfolioPolicyTest extends TestCase
use RefreshDatabase; use RefreshDatabase;
protected $policy; protected $policy;
protected $owner;
protected $user; protected $user;
protected $portfolio; protected $portfolio;
@@ -23,12 +24,12 @@ class PortfolioPolicyTest extends TestCase
$this->policy = new PortfolioPolicy(); $this->policy = new PortfolioPolicy();
$this->user = User::factory()->create(); $this->owner = User::factory()->create();
Auth::login($this->owner);
Auth::login($this->user);
$this->portfolio = Portfolio::factory()->create(); $this->portfolio = Portfolio::factory()->create();
// Attach the users to the portfolio // Attach the users to the portfolio
$this->user = User::factory()->create();
$this->portfolio->users()->syncWithoutDetaching([ $this->portfolio->users()->syncWithoutDetaching([
$this->user->id => [ $this->user->id => [
'full_access' => false, 'full_access' => false,
@@ -37,7 +38,7 @@ class PortfolioPolicyTest extends TestCase
]); ]);
} }
public function test_stranger_access_viaweb() public function test_stranger_access_via_web()
{ {
$user = User::factory()->create(); $user = User::factory()->create();