Laravel 4 - 从另一个表格的字段中获取价值并加入查询

时间:2014-08-21 19:47:53

标签: php mysql sql laravel-4

我在尝试处理此查询时遇到了很多麻烦。我是Laravel 4的新手,所以请轻松一点。

我所拥有的是2张桌子。上传和相册。目前,我正在尝试根据用户的ID输出所有相册,并抓取与该相册相关联的上传的最新缩略图。

这是我目前使用的代码:

DB::table("albums")
->select("albums.*","uploads.thumbnail")
->join("uploads", "uploads.albumid", "=", "albums.id")
->where("albums.userid", "=", Auth::user()->id)
->orderBy("uploads.id", "ASC")
->get()

输出错误。输出显示的几乎完全相反。它循环播放上传,而不是专辑并检索专辑表的第一条记录。

(
[0] => stdClass Object
    (
        [id] => 1
        [userid] => 1
        [private_code] => PJ3r6Ps3c5rRrceKRLvWmpk4o5GvHKHk7QCUnRkTmlwUnxnjmL9kVaOa1N4Tm124
        [slug] => album-test-1
        [name] => Album test 1
        [description] => Album test 1
        [privacy] => Public
        [created_at] => 
        [updated_at] => 
        [thumbnail] => 6s/zj/4e/6SZj4Ev409fU2b3NYHzgW7O9Jn3MFeDb_thumbnail.jpg
    )

[1] => stdClass Object
    (
        [id] => 1
        [userid] => 1
        [private_code] => PJ3r6Ps3c5rRrceKRLvWmpk4o5GvHKHk7QCUnRkTmlwUnxnjmL9kVaOa1N4Tm124
        [slug] => album-test-1
        [name] => Album test 1
        [description] => Album test 1
        [privacy] => Public
        [created_at] => 
        [updated_at] => 
        [thumbnail] => 17/zs/11/17zs11CwBKsPilpeMVjH7A7gTEcRxb4P_thumbnail.jpg
    )
)

我想循环浏览相册,同时检索该相册的最新上传缩略图,以用作相册的缩略图。

1 个答案:

答案 0 :(得分:0)

有些工作Eloquent更适合。由于这个不会比较2个连接表之间的字段,因此您可以使用Eloquent获得更好的性能和更轻松的时间,因为它使用了2个单独的SELECT查询。

相册型号:

public function uploads() { return $this->hasMany('Upload', 'albumId') }

上传模型:

public function album() { return $this->belongsTo('Album', 'albumId') }

<强>查询:

$albums = Album::with(['uploads' => function($query){
    $query->orderBy('created_at', 'desc')->take(1);
}])->where('userId', Auth::user()->id)->get();

在视图中获取缩略图:

@foreach($albums as $album)
    {{ $album->uploads->first()->thumbnail }}
@endforeach