我使用关系的条件/约束创建了一个模型游戏,如下所示:
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是结果集合。
MY PROBLEM:
当我尝试在不加载的情况下访问它时
$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上发布了这一期
发布于 2014-04-23 03:30:12
以防其他人遇到同样的问题。
请注意,关系必须是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。
发布于 2013-09-04 04:13:26
我认为这才是正确的方式:
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() );
发布于 2014-07-16 05:42:54
我想这就是你要找的(Laravel 4,参见http://laravel.com/docs/eloquent#querying-relations)
$games = Game::whereHas('video', function($q)
{
$q->where('available','=', 1);
})->get();
https://stackoverflow.com/questions/18520209
复制相似问题