如何检查用户是不是有喜欢的属性

Posted

技术标签:

【中文标题】如何检查用户是不是有喜欢的属性【英文标题】:How do I check if a user has like a property如何检查用户是否有喜欢的属性 【发布时间】:2019-09-08 18:19:49 【问题描述】:

我正在做一个房地产广告网站。在应用程序中,用户可以点赞或“星标”属性。这在已加星标的表中创建了一条带有 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 [];
    

【问题讨论】:

【参考方案1】:

您可以为此简单地在控制器中添加一个检查。你可以把你的代码改成这样:

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

【讨论】:

查询没问题。不过,我会将检查代码放在模型方法中,因为您需要在前端(更改like按钮的图标)和控制器(如答案中所示)中检查相同的东西)。 谢谢。我将查询提取到通过使用关系访问的 StarredProperty 属性模型。

以上是关于如何检查用户是不是有喜欢的属性的主要内容,如果未能解决你的问题,请参考以下文章

Facebook如何检查用户是不是喜欢页面并显示内容?

如何使用 Facebook 的 API 检查用户是不是喜欢我的 Facebook 页面或 URL

检查用户是不是喜欢页面的无缝方式

PHP Facebook SDK - 检查用户是不是喜欢粉丝专页

从消息列表中检查用户是不是喜欢 msg

如何检查用户电子邮件是不是已验证?