Skip to content

Instantly share code, notes, and snippets.

@raank
Created September 14, 2017 22:20
Show Gist options
  • Save raank/60e81c8ffde03afe873d11ad73ba68d0 to your computer and use it in GitHub Desktop.
Save raank/60e81c8ffde03afe873d11ad73ba68d0 to your computer and use it in GitHub Desktop.
<?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();
}
}
<?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