dtcmadj31951 2017-02-16 12:13
浏览 172

在php / laravel中定义类中的数组

I have a class called shoppingCart and i would like to define an array inside of it. But it seems i need to manually create an instance of an array to use it. I am sure there is a way but i can`t find it My shopping chart class

namespace App;

use Illuminate\Database\Eloquent\Model;
use App\Product;

class shoppingChart extends Model
{
    var $products = Array();
    var $productCount=0;

    public function ItemCount(){
       return count($products);
    }
}

When i try to use i get a null pointer exceptionn and whenn i checked it $products doesn`t seem to be in variable list.

 array_push($sc->products, "test");

I can do it as below. When i am using the array. Works fine.

public function addToBasket(Request $request)
{   
    $product = new Product();
    $product->id = Input::get('product_id');


    if($request->session()->has('shoppingCart')){
        $sc = $request->session()->get('shoppingCart');
        $sc->products = Array(); // If i remove this line code doesn`t work
        array_push($sc->products,$product);
        $sc->productCount=$sc->itemCount();
    }
}

Should i initiate the array everytime i use it ? Doesn`t make any sense to me..

  • 写回答

1条回答 默认 最新

  • 普通网友 2017-02-16 13:15
    关注

    Without knowing more about the architecture of your application i can't go into specifics but I have a feeling that you might not even need this array.

    If you are looking at a ShoppingCart has many Product's, then try using an eloquent "Many to Many" relationship using relationships \Illuminate\Database\Eloquent\Relations\HasMany.

    https://laravel.com/docs/5.4/eloquent-relationships#many-to-many

    By having this relationship you will be able to get all products related to you cart by going $cart->products which will return an eloquent Collection of the products associated with the cart.

    评论

报告相同问题?

悬赏问题

  • ¥15 HFSS 中的 H 场图与 MATLAB 中绘制的 B1 场 部分对应不上
  • ¥15 如何在scanpy上做差异基因和通路富集?
  • ¥20 关于#硬件工程#的问题,请各位专家解答!
  • ¥15 关于#matlab#的问题:期望的系统闭环传递函数为G(s)=wn^2/s^2+2¢wn+wn^2阻尼系数¢=0.707,使系统具有较小的超调量
  • ¥15 FLUENT如何实现在堆积颗粒的上表面加载高斯热源
  • ¥30 截图中的mathematics程序转换成matlab
  • ¥15 动力学代码报错,维度不匹配
  • ¥15 Power query添加列问题
  • ¥50 Kubernetes&Fission&Eleasticsearch
  • ¥15 報錯:Person is not mapped,如何解決?