使用laravel雄辩的从表A中检索所有列,从表B中检索一些列

时间:2018-06-20 09:41:53

标签: laravel

我正在尝试通过将images表加入到list表中来检索缩略图图像路径。因此,我在控制器中有以下查询。

$listings = Listing::select('listings.*, images.path as image_path')
    ->where('listings.ownerid', '=', $ownerid)
    ->leftJoin('images', 'listings.thumbId', '=', 'images.id')->get();

测试完该功能后,查询失败,因为laravel将查询解释为

select `listings`.`*, images`.`path` as `image_path` from `listings` left join `images` on `listings`.`thumbId` = `images`.`id` where `listings`.`ownerid` = 1)

请注意,星号(*)与“,images”一词结合在一起,使其成为'*, images'

没有laravel的奇怪错字,查询工作正常。如何解决这个问题?

2 个答案:

答案 0 :(得分:2)

您需要在查询中进行一项更改。您正在传递原始选择字段,因此需要使用selectRaw()而不是select()。喜欢

$listings = Listing::selectRaw('listings.*, images.path as image_path')
    ->where('listings.ownerid', '=', $ownerid)
    ->leftJoin('images', 'listings.thumbId', '=', 'images.id')->get();

尝试通过上述查询进行检查。

答案 1 :(得分:0)

我建议您使用Laravel Eloquent关系功能。由于上面的代码更像是查询生成器而不是口才的。让我们来看下面的示例:

您将拥有2个模型,每个表1个(listingsimages):

应用\列表模型:

<?php
...
use App\Image;
class Listing extends Eloquent {
    ...
    protected $table = 'listings';

    // define Eloquent Relationship of Listing model to Image model
    public function image() {
       return $this->belongsTo(Image::class, 'thumbId');
    }
    ...
}

应用\图片模型:

<?php
...
use App\Listing;
class Image extends Eloquent {
    ...
    protected $table = 'images';

    ...
    // define Eloquent Relationship of Image model to Listing model
    public function listings() {
        return $this->hasMany(Listing::class, 'thumbId');
    }

}

那么如何获取数据?

// get all listing data
$listings = Listing::all();

// loop through the data
foreach ($listing as $listing) {
    dump($listing->id);

    // because we have define the relationship, we can access the related data of image
    dump($listing->image->path);

    // call $this->image will return related Image model
    dump($listing->image);
} 

有关更多示例和说明,请参见Laravel official documentation。 希望对您有所帮助。