Если я сделаю это, я смог бы извлечь images()
для item
Laravel красноречивые отношения с построитель запросов
$items = Item::all();
foreach($items as $item){
$image = $item->images()->first();
}
Однако, если у меня был сложный запрос с помощью конструктора запросов. Я не смог бы получить из него images()
. Есть ли способ получить все данные отношений от Eloquent Models, учитывая, что это построитель запросов?
$items = DB::table('items as i')
->join('users AS u', 'i.user_id', '=', 'u.id')
->where('account_id', 5)->all();
foreach($items as $item){
$image = $item->images()->first();
}
Артикул
class Item extends Eloquent {
/**
* The database table used by the model.
*
* @var string
*/
protected $table = 'items';
public function images()
{
return $this->hasMany('Image');
}
public function user(){
return $this->belongsTo('User');
}
}
модель Image
class Image extends Eloquent {
/**
* The database table used by the model.
*
* @var string
*/
protected $table = 'images';
public function item(){
return $this->belongsTo('Item');
}
}
ОБНОВЛЕНО: Модель Добавлено Пользователь
class User extends Eloquent {
/**
* The database table used by the model.
*
* @var string
*/
protected $table = 'users';
public function items()
{
// foreign key outside using this pk
return $this->hasMany('Item');
}
}
да, извините, я забыл добавить 'all()' при копировании, потому что у меня была серия '-> where()'. Это работает для '$ item-> images() -> first()', но не работает для '$ item-> user-> name' любые идеи? Я получаю сообщение об ошибке «Попытка получить свойство не-объекта» – bman
$ item-> user() -> first() -> name –
Я обновил свои модели. У меня только 1 пользователь на элемент, а '$ item-> user-> name' работает, если я просто делаю' $ item = Item :: all(); '. У тебя есть идеи? – bman