根据条件合并两个查询结果

时间:2018-03-08 07:12:47

标签: php laravel laravel-5.5

我有两个查询结果。我需要根据条件合并查询结果。

$portfolio = DB::table('architects_portfolio')->get();

 $img=DB::table('architects_portfolio_images')
          ->distinct()->get(['architects_images_id']);

我的合并条件是

architects_portfolio.id = architects_portfolio_images.architects_images_id

我的第一个表'architects_portfolio'包含投资组合和第二个表'architects_portfolio_images',其中包含投资组合的图像。我现在只需要获得一个图像。但是我现在通过使用下面的代码获得投资组合的所有图像。但是我只需要一个

 $architect = User::find($user_id)->architect;               
 $portfolio = ArchitectsPortfolio::join('architects_portfolio_images as images', 'architects_portfolio.id', '=', 'images.architects_images_id')
            ->where('architects_portfolio.architects_id', $architect->id)
            ->select('architects_portfolio.id', 'architects_portfolio.architects_id', 'architects_portfolio.name', 'architects_portfolio.description', 'images.filename','images.architects_images_id')
            ->distinct()->get(['images.architects_images_id']);

我的桌子 architects_potfolio

architects_portfolio_images

4 个答案:

答案 0 :(得分:1)

foreach ($files as $file) {
    try {
        $fileLog = $file->moveTo($location));
    }
    catch(\Exception $e) {
        throw new \Exception($e->getMessage());
    }
}

return true;

答案 1 :(得分:1)

你应该试试这个:

$rsltArchitectDetails = DB::table('architects_portfolio')
                    ->select('architects_portfolio_images.architects_images_id')
                    ->join('architects_portfolio_images', 'architects_portfolio.id' , '=', 'architects_portfolio_images.architects_images_id')
                    ->distinct()
                    ->get();

答案 2 :(得分:0)

最好的方法是使用relationships,然后您可以加载包含相关图片的投资组合:

$portfolios = ArhitectPortfolio::with('images')->get();

要使其有效,您只需在images模型中定义ArhitectPortfolio关系:

public function images()
{
    return $this->hasMany(ArchitectPortfolioImage::class, 'architects_images_id');
}

答案 3 :(得分:0)

我们可以使用以下代码

而不是合并
$data = Architect::where("user_id", $user_id)->first();
$architect = User::find($user_id)->architect;
        $portfolio = ArchitectsPortfolio::where('architects_portfolio.architects_id', $architect->id)->paginate(6);
        foreach ($portfolio as $r) {
            $image = ArchitectsPortfolioImages::where('architects_images_id', $r->id)->first();
            if ($image) {
                $r->filename = $image->filename;
            }
        }