Skip to content

Instantly share code, notes, and snippets.

@bolechen
Created July 19, 2019 03:00
Show Gist options
  • Save bolechen/0c634a18d46a2aedbeb518a8176f8473 to your computer and use it in GitHub Desktop.
Save bolechen/0c634a18d46a2aedbeb518a8176f8473 to your computer and use it in GitHub Desktop.
Check if belongsToMany relation exists
<?php
namespace App\Traits;
use Illuminate\Database\Eloquent\Model;
trait HasPivotTrait
{
/**
* 检查多对多关系是否存在.
*
* @param string $relation
* @param Model $model
*
* @return bool
*/
public function hasPivot(string $relation, Model $model)
{
return (bool) $this->{$relation}()->wherePivot($model->getForeignKey(), $model->{$model->getKeyName()})->count();
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment