Laravel has_many。我这样做了吗?

时间:2013-01-21 15:57:57

标签: php laravel

我是Laravel(和OOP)的新手,我正在组建一家商店。我已经为我的产品图片建立了一个关系,它可以按照我的需要运行,但我只是想检查一下我是否正确/高效地完成了这项工作。如果有经验的Laravel可以将注意力集中在下面并建议改进或给我一些反馈,我们将不胜感激。

我的产品有很多产品图片。以下是我的产品和产品模型:

产品:

class Products extends Eloquent {

    public static $table = 'core_Products';
    ........
    public function ProductImages(){
        return $this->has_many('ProductImage', 'product_id');
    }
}

Productimage:

class ProductImage extends Eloquent{

    public static $table = 'core_productimages';

    public function product(){
        return $this->belongs_to('Product');
    }
}

我的产品控制器(这是我认为我可以更高效地工作的地方。当然我不需要传递product_id来检索图像。模型不应该已经知道这个吗?):

class Store_Product_Controller extends Base_Controller {

public function action_index($serfURL = "", $intSectionID, $pSerfURL = "", $intProductID)
{

            .......
    $view->productImages = Products::find($intProductID)->ProductImages()->get();

    return $view;       


    }

}

最后,我的观点:

foreach ($productImages as $image){
    echo $image->strImageURI . "<br/>";
}

1 个答案:

答案 0 :(得分:0)

在您的“产品”模型中,您可以调用方法images(),以便在控制器中只需拨打产品上的->images()即可。此外,您的模型应该是单一的,并且您的has_many查询不需要'product_id'。它看起来像这样:

产品型号:

class Product extends Eloquent {

    public static $table = 'core_Products';

    // ...

    public function images() {

        return $this->has_many('ProductImage');
    }
}

ProductImage Model:

class ProductImage extends Eloquent {

    public static $table = 'core_productimages';

    public function product() {

        return $this->belongs_to('Product');
    }
}

产品总监:

class Store_Product_Controller extends Base_Controller {

    public function action_index($serfURL = "", $intSectionID, $pSerfURL = "", $intProductID) {

        // ...

        $view->product = Product::find($intProductID);

        return $view;       
    }

}

产品视图:

foreach ($product->images as $image) {

    echo $image->strImageURI . "<br/>";
}
相关问题