How to alias in Laravel Eager Loading

前端 未结 2 592
不思量自难忘°
不思量自难忘° 2021-01-18 09:56

I need to alias when I do a Laravel eager loading:

$posts = Post::with(array(\'images as main_image\' => function($query) // do not run
            {
             


        
相关标签:
2条回答
  • 2021-01-18 10:05

    I don't think you can do that with Eloquent, but there would be a few work-arounds that might work.

    If you are using PHP 5.6, it's possible to alias the function.

    use function images as main_image;
    

    If you are using a version of PHP less than that, you can create a main_image() function and have it call images().

    public function main_image()
    {
        return $this->images();
    }
    
    0 讨论(0)
  • 2021-01-18 10:15

    Perfect! you give me the idea. Finally I've done this:

    Post.php

    public function main_image()
    {
        return $this->hasMany('FoodImage')->where('number','=','0');
    }
    
    public function gallery_images()
    {
        // for code reuse
        return $this->main_image();
    }
    

    PostController.php

    $posts = Post::with:with('main_image')->with('gallery_images')                    
                ->where('id', '=', $id)                    
                ->get();
    
    0 讨论(0)
提交回复
热议问题