Files
investbrain/app/Models/Portfolio.php
T

90 lines
1.9 KiB
PHP
Raw Normal View History

2024-08-01 13:53:10 -05:00
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Concerns\HasUuids;
2024-08-01 13:53:10 -05:00
use Illuminate\Database\Eloquent\Factories\HasFactory;
class Portfolio extends Model
{
use HasFactory;
use HasUuids;
2024-08-01 13:53:10 -05:00
protected $fillable = [
'title',
'notes',
'wishlist',
];
protected static function boot()
{
parent::boot();
static::saved(function ($model) {
2024-08-17 21:33:09 -05:00
2024-08-01 13:53:10 -05:00
self::syncUsers($model);
});
}
protected $hidden = [];
2024-08-04 18:27:47 -05:00
protected $casts = [
'wishlist' => 'boolean'
];
2024-08-01 13:53:10 -05:00
2024-08-15 21:35:43 -05:00
protected $with = ['users', 'transactions'];
2024-08-01 13:53:10 -05:00
public function users()
{
return $this->belongsToMany(User::class)->withPivot('owner');
}
2024-08-15 21:35:43 -05:00
public function holdings()
{
2024-08-28 23:32:01 -05:00
return $this->hasMany(Holding::class, 'portfolio_id')
->withMarketData()
2024-08-29 18:46:21 -05:00
->withPerformance();
2024-08-15 21:35:43 -05:00
}
2024-08-01 13:53:10 -05:00
2024-08-15 21:35:43 -05:00
public function transactions()
{
2024-08-17 21:33:09 -05:00
return $this->hasMany(Transaction::class)->orderBy('created_at', 'DESC');
2024-08-15 21:35:43 -05:00
}
public function daily_change()
{
return $this->hasMany(DailyChange::class);
}
2024-08-01 13:53:10 -05:00
2024-08-28 22:06:47 -05:00
public function scopeMyPortfolios()
{
return $this->whereHas('users', function ($query) {
$query->where('user_id', auth()->user()->id);
});
}
2024-08-01 13:53:10 -05:00
public function scopeWithoutWishlists()
{
return $this->where(['wishlist' => false]);
}
public function getOwnerIdAttribute()
{
return $this->users()->firstWhere('owner', 1)?->id;
}
public static function syncUsers(self $model) {
// make sure we don't remove owner access
$user_id[$model->owner_id ?? auth()->user()->id] = ['owner' => true];
// // add other users
// foreach(request()->users ?? [] as $id) {
// $user_id[$id] = ['owner' => false];
// };
// save
$model->users()->sync($user_id);
}
}