Sunday, 15 January 2012

php - Updating timestamps on attaching/detaching Eloquent relations -



php - Updating timestamps on attaching/detaching Eloquent relations -

i'm using laravel 4, , have 2 models:

class asset extends \eloquent { public function products() { homecoming $this->belongstomany('product'); } } class product extends \eloquent { public function assets() { homecoming $this->belongstomany('asset'); } }

product has standard timestamps on (created_at, updated_at) , i'd update updated_at field of product when attach/detach asset.

i tried on asset model:

class asset extends \eloquent { public function products() { homecoming $this->belongstomany('product')->withtimestamps(); } }

...but did nil @ (apparently). edit: apparently updating timestamps on pivot table, not updating them on relation's own table (ie. updates assets_products.updated_at, not products.updated_at).

i tried on asset model:

class asset extends \eloquent { protected $touches = [ 'products' ]; public function products() { homecoming $this->belongstomany('product'); } }

...which works, breaks seed calls asset::create([ ... ]); because apparently laravel tries phone call ->touchowners() on relation without checking if it's null:

php fatal error: phone call undefined method illuminate\database\eloquent\collection::touchowners() in /projectdir/vendor/laravel/framework/src/illuminate/database/eloquent/model.php on line 1583

the code i'm using add/remove assets this:

product::find( $validid )->assets()->attach( $anothervalidid ); product::find( $validid )->assets()->detach( $anothervalidid );

where going wrong?

you can manually using touch method:

$product = product::find($validid); $product->assets()->attach($anothervalidid); $product->touch();

but if don't want manually each time can simplify creating method in product model way:

public function attachasset($id) { $this->assets()->attach($id); $this->touch(); }

and can utilize way:

product::find($validid)->attachasset($anothervalidid);

the same can of course of study detach action.

and noticed have 1 relation belongstomany , other hasmany - should rather belongstomany in both because it's many many relationship

edit

if utilize in many models, create trait or create base of operations class extends eloquent next method:

public function attach($id, $relationship = null) { $relationship = $relationship ?: $this->relationship; $this->{$relationship}()->attach($id); $this->touch(); }

now, if need functionality need extend base of operations class (or utilize trait), , can add together product class 1 property:

private $relationship = 'assets';

now use:

product::find($validid)->attach($anothervalidid);

or

product::find($validid)->attach($anothervalidid, 'assets');

if need attach info updating updated_at field. same of course of study need repeat detaching.

php laravel eloquent

No comments:

Post a Comment