Как проверить, есть ли у пользователя свойство - PullRequest
3 голосов
/ 18 апреля 2019

Я делаю сайт по рекламе недвижимости.В приложении пользователи могут добавить или пометить свойство.Это создало запись в помеченной таблице с помощью property_id и user_id.

Я хочу проверить, нравится ли пользователю текущее свойство, чтобы ему снова не понравилось.

На данный момент это все на стороне API.

Вот мой контроллер

Это создает понравившуюся / помеченную запись.

public function store(Property $property, User $user, Request $request)
    {     
        $starred = StarredProperty::create(['property_id' => $property->id, 'user_id' => $user->id]);

        return $starred;
    }

Это модель помеченного свойства

<?php

namespace App;

use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\SoftDeletes;


class StarredProperty extends Model
{
    use SoftDeletes;

    protected $fillable = ['property_id', 'user_id'];
}

Это модель пользователя со связью для всех помеченных свойств.

<?php

namespace App;

use Illuminate\Notifications\Notifiable;
use Illuminate\Contracts\Auth\MustVerifyEmail;
use Illuminate\Foundation\Auth\User as Authenticatable;
use App\Property;
use App\StarredProperty;
use Tymon\JWTAuth\Contracts\JWTSubject;


class User extends Authenticatable implements JWTSubject
{
    use Notifiable;

    protected $fillable = [
        'first_name', 'last_name', 'username', 'email', 'phone_number', 'password',
    ];

    protected $hidden = [
        'password', 'remember_token',
    ];

    protected $casts = [
        'email_verified_at' => 'datetime',
    ];

    public function properties()
    {
        return $this->hasMany(Property::class);
    }

    public function starredProperties()
    {
        return $this->hasMany(StarredProperty::class);
    }


    public function getJWTIdentifier()
    {
        return $this->getKey();
    }


    public function getJWTCustomClaims()
    {
        return [];
    }
}

Ответы [ 2 ]

4 голосов
/ 18 апреля 2019

Вы можете просто добавить проверку в контроллере для этого. Вы можете изменить свой код на что-то вроде этого:

public function store(Property $property, User $user, Request $request)
{
    if (! $user->starredProperties()->where('property_id', $property->id)->exists()) {
        $starred = StarredProperty::create(['property_id' => $property->id, 'user_id' => $user->id]);

        return $starred;
   }

   // Return whatever else you want here if they have already starred the property
}
1 голос
/ 18 апреля 2019

В вашем контроллере для помеченного свойства, вы можете использовать метод firstOrcreate вместо create, как указано в документе Laravel.

eloquent # other-creation-method

...