【问题标题】:Get distinct attribute from database in Laravel从 Laravel 的数据库中获取不同的属性
【发布时间】:2014-11-11 19:08:59
【问题描述】:

我有两张桌子,一张叫"products",另一张叫"product_brands"

一个产品有一个品牌,一个品牌可以属于多个产品。

我有:

class Product extends Eloquent {
    protected $table = 'products';
    public function type() {
        return $this->hasOne('ProductTypes');
    }

    public function brand()
    {
        return $this->hasOne('ProductBrands', 'id', 'brand_id');
    }

    public function image() {
        return $this->hasMany('ProductImages');
    }

    public function toArray() {

        $ar = $this->attributes;

        $ar['type'] = $this->type;
        $ar['brand'] = $this->brand;

        return $ar;
    }

    public function getBrandAttribute() {
        $brand = $this->brand()->first();
        return (isset($brand->brand) ? $brand->brand : '');
    }
}

还有我的控制器:

class ProductsController extends BaseController {

    public function index($type_id) {
        $Product = new Product;
        $products = $Product->where('type_id', $type_id)->get();
        return View::make('products.products', array('products' => $products));
    }

}

理想情况下,我希望 "product_brands" 中的列与 "products" 中的列位于同一数组中,因此我尝试使用 toArray()getBrandAttribute() 进行这些操作,但是它不工作。

我该怎么做?

【问题讨论】:

    标签: php mysql laravel laravel-4


    【解决方案1】:

    我确定 getBrandAttribute 访问器与 brand 关系发生冲突。试试这个:

    class Product extends Eloquent {
        protected $table = 'products';
        public function type() {
            return $this->hasOne('ProductTypes');
        }
    
        public function productBrand() {
            return $this->hasOne('ProductBrands', 'id', 'brand_id');
        }
    
        public function image() {
            return $this->hasMany('ProductImages');
        }
    
        public function getBrandAttribute() {
            $brand = $this->productBrand()->first();
            return (isset($brand->brand) ? $brand->brand : '');
        }
    
        protected $appends = array('brand'); // this makes Laravel include the property in toArray
    
    }
    

    【讨论】:

      【解决方案2】:

      您应该将访问者更改为其他名称:

      public function getSpecBrandAttribute() {
          $brand = $this->brand()->first();
          return (isset($brand->brand) ? $brand->brand : '');
      }
      

      然后你应该在toArray 中使用:

      public function toArray() {
      
          $ar = $this->attributes;
      
          $ar['type'] = $this->type;
          $ar['brand'] = $this->spec_brand;
      
          return $ar;
      }
      

      这是因为您不应该创建与关系名称同名的字段。

      此外,由于它是一对多关系,可能对于brand(),您应该使用belongsTo 而不是hasOne

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2017-06-02
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2012-08-30
        • 1970-01-01
        相关资源
        最近更新 更多