laravel 如何用where条件访问模型hasMany Relation?

1l5u6lss  于 11个月前  发布在  其他
关注(0)|答案(9)|浏览(219)

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

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


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

我的问题:

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

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


一个异常被抛出,因为它说“Call to a member function count()on a non-object"。
使用

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


工作正常,但对我来说似乎很复杂,因为如果我不使用关系中的条件,我不需要加载相关模型。
我错过了什么吗?我如何确保,available_videos可以访问而不使用急切加载?
对于任何感兴趣的人,我也在http://forums.laravel.io/viewtopic.php?id=10470上发布了这个问题

p4tfgftt

p4tfgftt1#

我认为这是正确的方法:

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

字符串
然后你就得

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

vbkedwbf

vbkedwbf2#

//使用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);
}

niwlg2el

niwlg2el3#

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

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

})->get();

字符串

v2g6jxz6

v2g6jxz64#

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

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

字符串

swvgeqrz

swvgeqrz5#

以防其他人遇到同样的问题。
注意,关系必须是camelcase。所以在我的例子中,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总是返回一个Collection。

92dk7w1h

92dk7w1h6#

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

字符串

v440hwme

v440hwme7#

我已经通过将关联数组作为Builder::with方法的第一个参数传递来修复了类似的问题。
假设您想通过一些动态参数包含子关系,但不想过滤父结果。

Model.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}%");
        }
    ]
);


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

4uqofj5v

4uqofj5v8#

Model(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;
}

字符串
Controller(App\Http\Controller\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

igetnqfo

igetnqfo9#

要使用where条件访问hasMany关系,可以使用whereHas方法。
下面是一个例子:

$orders = Order::whereHas('items', function ($query) {
   $query->whereNotNull('merchant_referral_percentage');
})->get();

字符串
在本例中,Order是与物料具有hasMany关系的模型。whereHas方法用于根据物料关系的条件筛选订单。本例中的条件是merchant_referral_percentage列不应为null。
您可以修改where回调函数中的条件以满足您的特定需要。

相关问题