Created
September 14, 2017 22:20
-
-
Save raank/60e81c8ffde03afe873d11ad73ba68d0 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 LaraShop\Factories\Entities; | |
| use Illuminate\Database\Eloquent\Model; | |
| use LaraShop\Marks\Entities\Mark; | |
| class Factory extends Model | |
| { | |
| protected $table = 'factories'; | |
| protected $fillable = []; | |
| protected $appends = []; | |
| /** | |
| * @return \Illuminate\Database\Eloquent\Relations\BelongsToMany | |
| */ | |
| public function marks() | |
| { | |
| return $this->belongsToMany(Mark::class, 'factories_marks', 'factory_id', 'mark_id')->withTimestamps(); | |
| } | |
| } |
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 LaraShop\Marks\Entities; | |
| use Illuminate\Database\Eloquent\Model; | |
| use LaraShop\Factories\Entities\Factory; | |
| class Mark extends Model | |
| { | |
| protected $table = 'marks'; | |
| protected $fillable = []; | |
| protected $appends = [ | |
| 'business_total' | |
| ]; | |
| /** | |
| * Aqui que eu gostaria de usar o "Eager Loading" | |
| * @return int | |
| */ | |
| public function getBusinessTotalAttribute() | |
| { | |
| $id = $this->attributes['id']; | |
| // Como eu gostaria | |
| return Factory::with(['marks' => function($query) use($id) { | |
| $query->where('id', '=', $id); | |
| ])->count(); | |
| // Gambiarra | |
| foreach (Factory::all() as $factory) { | |
| foreach($factory->marks as $mark) { | |
| if($mark->id == $id) { | |
| $marks[] = $mark; | |
| } | |
| } | |
| } | |
| return isset($marks) ? count($marks) : 0; | |
| } | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment