Как получить доступ к модели hasMany Relation с условием?
Я создал модельную игру, используя условие/ограничение для отношения следующим образом:
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();
Исключение выбрано, поскольку оно говорит: "Вызовите функцию-член() для не-объекта".
Использование
$game = Game::find(1);
$game->load('available_videos');
$game->available_videos->count();
работает отлично, но мне кажется довольно сложным, поскольку мне не нужно загружать связанные модели, если я не использую условия в своих отношениях.
Я что-то пропустил? Как я могу гарантировать, что доступное_videos доступно без использования загруженной загрузки?
Для всех, кого это интересует, я также разместил эту проблему на http://forums.laravel.io/viewtopic.php?id=10470
Ответы
Ответ 1
На всякий случай кто-то сталкивается с теми же проблемами.
Обратите внимание, что отношения должны быть верблюдами. Поэтому в моем случае доступный_videos() должен быть доступен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 value on the "relationships" array.
$camelKey = camel_case($key);
if (method_exists($this, $camelKey))
{
return $this->getRelationshipFromMethod($key, $camelKey);
}
}
Это также объясняет, почему мой код работал, когда я загружал данные, используя метод load() раньше.
Во всяком случае, мой пример работает отлично, и $model- > availableVideos всегда возвращает коллекцию.
Ответ 2
Я думаю, что это правильный путь:
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() );
Ответ 3
Я думаю, что это то, что вы ищете (Laravel 4, см. http://laravel.com/docs/eloquent#querying-relations)
$games = Game::whereHas('video', function($q)
{
$q->where('available','=', 1);
})->get();
Ответ 4
//ниже для v4 какой-то версии
public function videos() {
$instance =$this->hasMany('Video');
$instance->getQuery()->where('available','=', 1);
return $instance
}
//v5
public function videos() {
return $this->hasMany('Video')->where('available','=', 1);
}
Ответ 5
Если вы хотите применить условие к реляционной таблице, вы можете использовать и другие решения. Это решение работает с моего конца.
public static function getAllAvailableVideos() {
$result = self::with(['videos' => function($q) {
$q->select('id', 'name');
$q->where('available', '=', 1);
}])
->get();
return $result;
}
Ответ 6
Создана ли модель для "Роли".
Проверьте, существует ли проблема даже после создания модели для роли.
Ответ 7
Модель (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