【问题标题】:Accessing a hasMany relation function via Collection通过 Collection 访问 hasMany 关系函数
【发布时间】:2020-03-27 05:01:45
【问题描述】:

我正在尝试获取所有用户通知,具体取决于用户是买家还是卖家(可以同时是两者)。我在通知表中创建了两个函数来相互过滤。 我的目标是最终运行:

$notifications = Auth::user()->notifications()->getBuyerNotifications();

$notifications = Auth::user()->notifications()->getSellerNotifications();

我遇到了一个问题:Call to undefined method Illuminate\Database\Eloquent\Relations\HasMany

用户模型:

public function notifications() {
   return $this->hasMany('App\Notification', 'user_id', 'id');
}

通知模型:

public function user() {
  return $this->belongsTo('App\User', 'id', 'user_id');
}

public static function getBuyerNotifications() {
  return self::whereNotNull('buyer_id')
              ->whereNull('deleted_at')
              ->get();

}

public static function getSellerNotifications() {
      return $this->whereNotNull('seller_id')
                    ->whereNull('deleted_at')
                    ->get();
}

如果他们是买家,我想运行该命令以获取所有用户通知:$notifications = Auth::user()->notifications()->getBuyerNotifications();

【问题讨论】:

  • 为什么是那些静态方法?
  • @jeremykenedy 正在测试一些东西 - 不需要它是静态的
  • 只是好奇,当您只有$notifications = Auth::user()->notifications 时会发生错误吗?
  • @jeremykenedy 没有错误。只返回一个通知集合
  • @jeremykenedy 现在我可以在一行中执行 notification()->whereNotNull('buyer_id') 等,但将它放在一个函数中将是理想的,因此任何人都可以调用它

标签: php laravel laravel-5 laravel-7


【解决方案1】:

首先,你不需要使用whereNull('deleted_at'),你可以在你的模型中导入softDeletes Trait:

use Illuminate\Database\Eloquent\SoftDeletes;
...
class Notification extends Model {
    use SoftDeletes;
    ...
}

Laravel 会自动在 Eloquent-Builder 上使用 whereNull('deleted_at')

其次,你不能在Illuminate\Database\Eloquent\Relations\HasMany上使用静态方法。

改用scope 方法:

public function scopeBuyerNotifications($query) {
    return $query->whereNotNull('buyer_id');
}
public function scopeSellerNotifications($query) {
    return $query->whereNotNull('seller_id');
}

所以你可以找到这样的通知:

$notifications = Auth::user()->notifications()->sellerNotifications()->get();

$notifications = Auth::user()->notifications()->buyerNotifications()->get();

【讨论】:

  • 有效!谢谢
【解决方案2】:

Auth::user() 使用会话数据。

试试这个:

optional(User::find(Auth::id())->notifications)->getBuyerNotifications;

$userId = 1; // Example id you can just pass the user Id.
User::find($userId)->notifications->getBuyerNotifications;

【讨论】:

    【解决方案3】:

    您可以在用户模型中添加其他两种方法,如下所示

    public function getBuyerNotifications() {
        return $this->hasMany('App\Notification', 'buyer_id', 'id');
    }
    public function getSellerNotifications() {
        return $this->hasMany('App\Notification', 'seller_id', 'id');
    }
    

    你可以直接从用户实例调用它

    $user->getBuyerNotifications();
    $user->getSellerNotifications();
    

    【讨论】:

      猜你喜欢
      • 2019-10-01
      • 2023-02-02
      • 1970-01-01
      • 2019-04-04
      • 2017-02-14
      • 1970-01-01
      • 1970-01-01
      • 2014-09-30
      • 1970-01-01
      相关资源
      最近更新 更多