Domanda

I have two tables, one called invoice, the other called invoice_products. invoice contains the basic info for the invoice, but no total. however invoice_products holds the actual items attached to the order. this allows me to customize the order simply by adding a new invoice_product. the total is done by running a function that loops through the attached invoice_products and adds them up. what i want to know is:

can i use a mutator or some other trick to have invoice->total already have it populated without calling the function to do so directly

$invoice = Invoice::find(1);
echo $invoice->total;

I've looked at the documentation for accessors and mutators, and it seems to be what i'm doing but i can't find any examples online of actually manipulating the tables related to the current model.

thanks.

È stato utile?

Soluzione

Just add a new function total() to your model:

public function total()
{
    // You can access the model using $this
    // example: $this->id
    // ...
    // Your logic to get the count
    // ...

    $this->total = $theGeneratedCount;
    return $this;
}

$invoice = find(1)->total(); // returns a Invoice model
echo $invoice->total;

This way you could continue chaining. Else, you could just return the count, but then you won't be able to chain.

...
return $theGeneratedCount;
...

$invoice = find(1);
echo $invoice->total(); // returns the count

To get $invoice->total to work you need to specify a __get() magic method:

public function __get($name)
{
    if(method_exists($this, $name) return $this->{$name}()
    return parent::__get($name);
}

Altri suggerimenti

If you want to use accessors, in your Invoice model you can define a method

public function getTotalAttribute()
{
  // You can access the related model e.g if your invoice is related to a product model          
  //you can access the products collection by the relationship name

  $this->products->...

  // calculate the total ... 

   return $total;
}

Then you can call the method as you want $invoice->total, the attribute will be available in the $invoice object.

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top