How to access model hasMany Relation with where condition?

前端 未结 8 1354
迷失自我
迷失自我 2020-12-08 00:02

I created a model Game using a condition / constraint for a relation as follows:

class Game extends Eloquent {
             


        
8条回答
  •  暖寄归人
    2020-12-08 00:50

    Just in case anyone else encounters the same problems.

    Note, that relations are required to be camelcase. So in my case available_videos() should have been availableVideos().

    You can easily find out investigating the Laravel source:

    // Illuminate\Database\Eloquent\Model.php
    ...
    /**
     * Get an attribute from the model.
     *
     * @param  string  $key
     * @return mixed
     */
    public function getAttribute($key)
    {
        $inAttributes = array_key_exists($key, $this->attributes);
    
        // If the key references an attribute, we can just go ahead and return the
        // plain attribute value from the model. This allows every attribute to
        // be dynamically accessed through the _get method without accessors.
        if ($inAttributes || $this->hasGetMutator($key))
        {
            return $this->getAttributeValue($key);
        }
    
        // If the key already exists in the relationships array, it just means the
        // relationship has already been loaded, so we'll just return it out of
        // here because there is no need to query within the relations twice.
        if (array_key_exists($key, $this->relations))
        {
            return $this->relations[$key];
        }
    
        // If the "attribute" exists as a method on the model, we will just assume
        // it is a relationship and will load and return results from the query
        // and hydrate the relationship's value on the "relationships" array.
        $camelKey = camel_case($key);
    
        if (method_exists($this, $camelKey))
        {
            return $this->getRelationshipFromMethod($key, $camelKey);
        }
    }
    

    This also explains why my code worked, whenever I loaded the data using the load() method before.

    Anyway, my example works perfectly okay now, and $model->availableVideos always returns a Collection.

提交回复
热议问题