Laravel where on relationship object

前端 未结 6 793
余生分开走
余生分开走 2020-12-12 20:21

I\'m developing a web API with Laravel 5.0 but I\'m not sure about a specific query I\'m trying to build.

My classes are as follows:

class Event exte         


        
6条回答
  •  我在风中等你
    2020-12-12 20:45

    I created a custom query scope in BaseModel (my all models extends this class):

    /**
     * Add a relationship exists condition (BelongsTo).
     *
     * @param  Builder        $query
     * @param  string|Model   $relation   Relation string name or you can try pass directly model and method will try guess relationship
     * @param  mixed          $modelOrKey
     * @return Builder|static
     */
    public function scopeWhereHasRelated(Builder $query, $relation, $modelOrKey = null)
    {
        if ($relation instanceof Model && $modelOrKey === null) {
            $modelOrKey = $relation;
            $relation   = Str::camel(class_basename($relation));
        }
    
        return $query->whereHas($relation, static function (Builder $query) use ($modelOrKey) {
            return $query->whereKey($modelOrKey instanceof Model ? $modelOrKey->getKey() : $modelOrKey);
        });
    }
    

    You can use it in many contexts for example:

    Event::whereHasRelated('participants', 1)->isNotEmpty(); // where has participant with id = 1 
    

    Furthermore, you can try to omit relationship name and pass just model:

    $participant = Participant::find(1);
    Event::whereHasRelated($participant)->first(); // guess relationship based on class name and get id from model instance
    

提交回复
热议问题