Refactoring relationships method

pull/879/head
Kei 1 year ago
parent 8b5426d41f
commit d8da0a5270

@ -42,7 +42,7 @@ class UrlController extends Controller
*/
public function showDetail(string $urlKey)
{
$url = Url::with('visit')->whereKeyword($urlKey)->firstOrFail();
$url = Url::with('visits')->whereKeyword($urlKey)->firstOrFail();
$data = [
'url' => $url,
'visit' => new \App\Models\Visit,

@ -82,7 +82,7 @@ final class UserTable extends PowerGridComponent
{
return PowerGrid::eloquent()
->addColumn('name', function (User $user) {
$url = $user->url();
$url = $user->urls();
$urlCountTitle = $url->count().' '.Str::plural('url', $url->count()).' created';
return $user->name.' <span title="'.$urlCountTitle.'">('.$url->count().')</span>';

@ -64,7 +64,7 @@ class Url extends Model
/**
* @return \Illuminate\Database\Eloquent\Relations\HasMany
*/
public function visit()
public function visits()
{
return $this->hasMany(Visit::class);
}
@ -145,10 +145,10 @@ class Url extends Model
*/
public function numberOfClicks(int $urlId, bool $unique = false): int
{
$total = self::find($urlId)->visit()->count();
$total = self::find($urlId)->visits()->count();
if ($unique) {
$total = self::find($urlId)->visit()
$total = self::find($urlId)->visits()
->whereIsFirstClick(true)
->count();
}

@ -53,7 +53,7 @@ class User extends Authenticatable
/**
* @return \Illuminate\Database\Eloquent\Relations\HasMany
*/
public function url()
public function urls()
{
return $this->hasMany(Url::class);
}

@ -3,6 +3,7 @@
namespace Tests\Unit\Models;
use App\Models\Url;
use App\Models\User;
use App\Models\Visit;
use Tests\TestCase;
@ -43,7 +44,8 @@ class UrlTest extends TestCase
'user_id' => $this->admin()->id,
]);
$this->assertTrue($url->user()->exists());
$this->assertEquals(1, $url->user->count());
$this->assertInstanceOf(User::class, $url->user);
}
/**
@ -71,7 +73,7 @@ class UrlTest extends TestCase
'url_id' => $url->id,
]);
$this->assertTrue($url->visit()->exists());
$this->assertTrue($url->visits()->exists());
}
/**

@ -20,7 +20,7 @@ class UserTest extends TestCase
'user_id' => $user->id,
]);
$this->assertTrue($user->url()->exists());
$this->assertTrue($user->urls()->exists());
}
/**

@ -19,10 +19,11 @@ class VisitTest extends TestCase
*/
public function belongsToUrl()
{
$visit = Visit::factory()->create([
'url_id' => fn () => Url::factory()->create()->id,
]);
$visit = Visit::factory()
->for(Url::factory()->create())
->create();
$this->assertTrue($visit->url()->exists());
$this->assertEquals(1, $visit->url->count());
$this->assertInstanceOf(Url::class, $visit->url);
}
}

Loading…
Cancel
Save