如何访问模型hasMany与where where条件?

Rem*_*ben 43 laravel eloquent laravel-4

我使用关系的条件/约束创建了一个模型游戏,如下所示:

class Game extends Eloquent {
    // many more stuff here

    // relation without any constraints ...works fine 
    public function videos() {
        return $this->hasMany('Video');
    }

    // results in a "problem", se examples below
    public function available_videos() {
        return $this->hasMany('Video')->where('available','=', 1);
    }
}
Run Code Online (Sandbox Code Playgroud)

什么时候使用它像这样:

$game = Game::with('available_videos')->find(1);
$game->available_videos->count();
Run Code Online (Sandbox Code Playgroud)

一切正常,因为角色是最终的集合.

我的问题:

当我试图访问它而没有急切加载

$game = Game::find(1);
$game->available_videos->count();
Run Code Online (Sandbox Code Playgroud)

抛出异常,因为它表示" 在非对象上调用成员函数count() ".

运用

$game = Game::find(1);
$game->load('available_videos');
$game->available_videos->count();
Run Code Online (Sandbox Code Playgroud)

工作正常,但对我来说似乎很复杂,因为我不需要加载相关的模型,如果我不在我的关系中使用条件.

我错过了什么吗?我怎样才能确保可以在不使用预先加载的情况下访问available_videos?

对于任何有兴趣的人,我也在http://forums.laravel.io/viewtopic.php?id=10470上发布了这个问题.

Ant*_*iro 66

我认为这是正确的方法:

class Game extends Eloquent {
    // many more stuff here

    // relation without any constraints ...works fine 
    public function videos() {
        return $this->hasMany('Video');
    }

    // results in a "problem", se examples below
    public function available_videos() {
        return $this->videos()->where('available','=', 1);
    }
}
Run Code Online (Sandbox Code Playgroud)

然后你必须这样做

$game = Game::find(1);
var_dump( $game->available_videos()->get() );
Run Code Online (Sandbox Code Playgroud)

  • 将功能名称更新为`availableVideos`。如果只需要视频来返回可用视频,则可以执行以下操作:返回$ this-> hasMany('Video')-> where('available','=',1);` (3认同)

Sab*_*ett 23

我认为这就是你要找的东西(Laravel 4,见http://laravel.com/docs/eloquent#querying-relations)

$games = Game::whereHas('video', function($q)
{
    $q->where('available','=', 1);

})->get();
Run Code Online (Sandbox Code Playgroud)


xsi*_*n T 15

//较低的v4某个版本

public function videos() {
    $instance =$this->hasMany('Video');
    $instance->getQuery()->where('available','=', 1);
    return $instance
}
Run Code Online (Sandbox Code Playgroud)

// V5

public function videos() {
    return $this->hasMany('Video')->where('available','=', 1);
}
Run Code Online (Sandbox Code Playgroud)

  • 对于v5,您可以执行以下操作:`return $ this-> hasMany('Video')-> where('available','=',1);`使它更整洁 (2认同)

Rem*_*ben 12

以防万一其他人遇到同样的问题.

注意,关系必须是camelcase.所以在我的情况下,available_videos()应该是可用的视频().

您可以轻松找到调查Laravel源代码:

// 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);
    }
}
Run Code Online (Sandbox Code Playgroud)

这也解释了为什么我的代码工作,每当我使用load()方法加载数据之前.

无论如何,我的例子现在完全没问题,$ model-> availableVideos总是返回一个Collection.

  • @Vineet抱歉,没有.MVC与URL结构无关.routes.php文件定义了从url到controller的映射. (8认同)

小智 9

 public function outletAmenities()
{
    return $this->hasMany(OutletAmenities::class,'outlet_id','id')
        ->join('amenity_master','amenity_icon_url','=','image_url')
        ->where('amenity_master.status',1)
        ->where('outlet_amenities.status',1);
}
Run Code Online (Sandbox Code Playgroud)


Vit*_*lii 8

我通过将关联数组作为方法内的第一个参数传递来解决了类似的问题Builder::with

想象一下,您想要通过一些动态参数包含子关系,但不想过滤父结果。

模型.php

public function child ()
{
    return $this->hasMany(ChildModel::class);
}
Run Code Online (Sandbox Code Playgroud)

然后,在其他地方,当您放置逻辑时,您可以执行诸如按HasMany类过滤关系之类的操作。例如(与我的情况非常相似):

$search = 'Some search string';
$result = Model::query()->with(
    [
        'child' => function (HasMany $query) use ($search) {
            $query->where('name', 'like', "%{$search}%");
        }
    ]
);
Run Code Online (Sandbox Code Playgroud)

然后,您将过滤所有子结果,但父模型不会过滤。感谢您的关注。


Nik*_* K. 7

如果您想在关系表上应用条件,那么您也可以使用其他解决方案。

public static function getAllAvailableVideos() {
        $result = self::with(['videos' => function($q) {
                        $q->select('id', 'name');
                        $q->where('available', '=', 1);
                    }])                    
                ->get();
        return $result;
    }
Run Code Online (Sandbox Code Playgroud)