76

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

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);
    }
}

当以某种方式使用它时:

$game = Game::with('available_videos')->find(1);
$game->available_videos->count();

一切正常,因为角色是结果集合。

我的问题:

当我尝试在不急于加载的情况下访问它时

$game = Game::find(1);
$game->available_videos->count();

抛出异常,因为它说“调用非对象上的成员函数 count() ”。

使用

$game = Game::find(1);
$game->load('available_videos');
$game->available_videos->count();

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

我错过了什么吗?我如何确保在不使用预加载的情况下可以访问 available_videos?

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

4

8 回答 8

103

I think that this is the correct way:

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);
    }
}

And then you'll have to

$game = Game::find(1);
var_dump( $game->available_videos()->get() );
于 2013-09-03T20:13:25.710 回答
36

我认为这就是您正在寻找的(Laravel 4,请参阅http://laravel.com/docs/eloquent#querying-relations

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

})->get();
于 2014-07-15T21:42:54.257 回答
33

//使用getQuery()添加条件

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

// 简单地

public function videos() {
    return $this->hasMany('Video')->where('available','=', 1);
}
于 2016-04-14T03:09:44.333 回答
16

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

请注意,关系必须是驼峰式。所以在我的情况下,available_videos() 应该是 availableVideos()。

你可以很容易地找到调查 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);
    }
}

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

无论如何,我的示例现在工作得很好,并且 $model->availableVideos 总是返回一个集合。

于 2014-04-22T19:30:12.157 回答
13

如果您想在关系表上应用条件,您也可以使用其他解决方案。这个解决方案对我来说是有效的。

public static function getAllAvailableVideos() {
        $result = self::with(['videos' => function($q) {
                        $q->select('id', 'name');
                        $q->where('available', '=', 1);
                    }])                    
                ->get();
        return $result;
    }
于 2016-10-05T08:01:51.847 回答
4

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

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

模型.php

public function child ()
{
    return $this->hasMany(ChildModel::class);
}

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

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

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

于 2019-08-05T12:17:58.433 回答
4
 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);
}
于 2019-12-29T15:35:34.083 回答
2

型号(App\Post.php):

/**
 * Get all comments for this post.
 */
public function comments($published = false)
{
    $comments = $this->hasMany('App\Comment');
    if($published) $comments->where('published', 1);

    return $comments;
}

控制器(App\Http\Controllers\PostController.php):

/**
 * Display the specified resource.
 *
 * @param int $id
 * @return \Illuminate\Http\Response
 */
public function post($id)
{
    $post = Post::with('comments')
        ->find($id);

    return view('posts')->with('post', $post);
}

刀片模板(posts.blade.php):

{{-- Get all comments--}}
@foreach ($post->comments as $comment)
    code...
@endforeach

{{-- Get only published comments--}}
@foreach ($post->comments(true)->get() as $comment)
    code...
@endforeach
于 2018-12-14T10:16:47.443 回答