From 55ad4e9a6db745581d99506e0b9d1438b934be3d Mon Sep 17 00:00:00 2001 From: kapil verma Date: Tue, 4 Sep 2012 02:40:28 +0530 Subject: [PATCH] Added a method to fluently set belongs-to relation This method spun off from a discussion in IRC. What this enables is this: $user->comments()->insert($comment_data)->article()->bind($article->id) --- .../eloquent/relationships/belongs_to.php | 16 ++++++++++++++++ 1 file changed, 16 insertions(+) diff --git a/laravel/database/eloquent/relationships/belongs_to.php b/laravel/database/eloquent/relationships/belongs_to.php index ef257836..6a2c1116 100644 --- a/laravel/database/eloquent/relationships/belongs_to.php +++ b/laravel/database/eloquent/relationships/belongs_to.php @@ -110,5 +110,21 @@ class Belongs_To extends Relationship { { return $this->base->get_attribute($this->foreign); } + + /** + * Bind an object over a belongs-to relation using its id. + * + * @return Eloquent + */ + + public function bind($id) + { + if((int) $this->foreign_value() === (int) $id) + return $this->base; + + $this->base->fill(array($this->foreign => $id))->save(); + + return $this->base; + } } \ No newline at end of file