I have:
ItemRepo
class ItemRepo {
...
public function findByNameAndDate($name, Carbon $date, $with = null) {
$item = Item::where('name', $name)->where(DB::raw('DATE(created_at)'), $date->toDateString());
if($with) {
$item->with($with);
}
return $item->first();
}
}
Which is called from:
ItemController
...
use App\Repos\ItemRepo;
...
class ItemController extends Controller
{
protected $repo;
function __construct() {
$this->repo = new ItemRepo();
}
public function show($day, $month, $year, $name) {
$date = Carbon::createFromDate($year, $month, $day);
$item = $this->repo->findByNameAndDate($name, $date, 'likes');
return $item;
}
}
You see I have an optional $with
parameter for when I want to bring back any relationships, in this case I wanted all the likes for an item.
Is this the right way to do it? or would it be better to simply get the Item model, then pass that model to a LikeRepo
that e.g. has a function called countLikes
or getLikes
. However in that case you are doing two queries and not a single larger one (which is why I am unsure of which is the best way to go).
via Chebli Mohamed
Aucun commentaire:
Enregistrer un commentaire