Last active
February 10, 2016 18:23
-
-
Save RDelorier/d84ab077e3fe488b0cb1 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
namespace App\Models; | |
use App\Models\Traits\HasScopedRelations; | |
use Illuminate\Database\Eloquent\Model; | |
class User extends Model | |
{ | |
use HasScopedRelations; | |
public function addresses() | |
{ | |
return $this->hasMany('App\Models\Address'); | |
} | |
public function primaryAddress() | |
{ | |
return $this->hasOneScoped('App\Models\Address')->with(['type' => 'primary']); | |
} | |
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
namespace App\Models\Relations; | |
use Illuminate\Database\Eloquent\Relations\HasOne; | |
class HasOneScoped extends HasOne | |
{ | |
protected $attributes = []; | |
public function addConstraints() | |
{ | |
parent::addConstraints(); | |
if(static::$constraints){ | |
$this->query->where($this->attributes); | |
} | |
} | |
public function addEagerConstraints(array $models) | |
{ | |
parent::addEagerConstraints($models); | |
$this->query->where($this->attributes); | |
} | |
public function create(array $attributes) | |
{ | |
return parent::create(array_merge($attributes, $this->attributes)); | |
} | |
/** | |
* Add attribute scope. | |
* | |
* @param $attributes | |
* | |
* @return $this | |
*/ | |
public function with($attributes) | |
{ | |
$this->attributes = $attributes; | |
$this->query->where($attributes); | |
return $this; | |
} | |
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
namespace App\Models\Traits; | |
use App\Models\Relations\HasOneScoped; | |
/** | |
* Trait HasScopedRelations can be added to an eloquent model to extend functionality | |
*/ | |
trait HasScopedRelations | |
{ | |
/** | |
* @param $related | |
* @param null $foreignKey | |
* @param null $localKey | |
* | |
* @return HasOneScoped | |
*/ | |
public function hasOneScoped($related, $foreignKey = null, $localKey = null) | |
{ | |
$foreignKey = $foreignKey ?: $this->getForeignKey(); | |
$instance = new $related; | |
$localKey = $localKey ?: $this->getKeyName(); | |
return new HasOneScoped($instance->newQuery(), $this, $instance->getTable().'.'.$foreignKey, $localKey); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
@antwaanvh