1
votes

I'm using CakePHP 2.0.5 (but this isn't necessarily a cakephp specific question). I have a Coupon and a User model. Each time a user prints a coupon (proccessed by: Coupon Controller):

class CouponsController extends AppController {
    public function printcoupon($id = null) {
        // code
    }
}

I want to save the information to a "coupons_printed" table (id/coupon_id/user_id/created). Should I create a new model for this, or should I just create a function inside of the Coupon model similar to (and call it in the controller each time that page is viewed)?:

class Coupon extends AppModel {
    function insertIntoPrinted($id) { 
        $this->query("UPDATE coupons_printed SET .....");  
    } 

}
2

2 Answers

2
votes

Whatever you do, a raw SQL query is not the best way to go. Always use CakePHP methods if at all possible (and almost always it is possible).

You should put the insertIntoPrinted() function in the CouponsPrinted model (although, as a side note, PrintedCoupon would be a more natural way to name the model...) You can then add a HasMany relationship to the Coupon model ($hasMany = array( 'CouponsPrinted' )) and call the function in the CouponsController:

public function printcoupon($id = null) {
    $this->Coupon->CouponsPrinted->insertIntoPrinted( $id );
}
0
votes

CakePHP's model has a thing call association.
In your case, Coupon has a hasMany association with coupons_printed.
You can create a new model, or query using the association in the Coupon model, the generated queries will be the same, I believe.

Your CouponsController already depend on Coupon Model, so not creating another model is a better solution.