如何优化我的控制器,使其运行 1 个查询而不是 3 个

How can I optimize my controller so it runs 1 query instead of 3

下面是我在Laravel 9中制作的一个应用程序的控制器。它运行相同的 SQL 3 次以获得 id。有没有办法优化它,让它只运行一次?

class ProductController extends Controller
{
    public function index()
    {
        return view('products.index', [
            'products' => product::paginate(6)->withQueryString()
        ]);
    }

    public function show($id, $name = null)
    {
        // Checks if product exists
        if (!product::find($id)) {
            return dd('Product not found');
        }

        $slug = Str::of(product::find($id)->name)->slug('-');

        //Checks if product name is set
        if (!$name || $name != $slug) {
            return redirect()->route('products.show', [
                'id' => $id,
                'name' => $slug
            ]);
        }

        //if all above is coorect then return view
        return view('products.show', [
            'product' => product::find($id)
        ]);
    }
}

在您的 public function show($id, $name = null) 中,首先将 id 的值获取到一个变量中: $productById = product::find($id);

随后在函数中到处使用 $productById 而不是 product::find($id)

(我只是用更详细的方式描述了@lagbox 评论的内容。)

只需使用变量 $product.

class ProductController extends Controller {

    public function index() {
        return view('products.index', [
            'products' => product::paginate(6)->withQueryString()
        ]);
    }

    public function show($id, $name = null) {

        $product = product::find($id);

        //Checks if product exists
        if (!$product) {
            return dd('Product not found');
        }

        $slug = Str::of($product->name)->slug('-');

        //Checks if product name is set
        if (!$name || $name != $slug) {
            return redirect()->route('products.show', [
                'id' => $id,
                'name' => $slug
            ]);
        }

        //if all above is coorect then return view
        return view('products.show', [
            'product' => $product
        ]);
    }
}

变变变变!

A variable in PHP is a name of memory location that holds data. In PHP, a variable is declared using $ sign followed by variable name. The main way to store information in the middle of a PHP program is by using a variable.

所以一个变量可以代表整个代码块中的一个值! 尝试为您的查询定义一个变量,然后尝试在您的代码需要使用它的任何地方调用它:

$product = product::find($id);