I need to make a function witch can be called in a foreach loop such has :
foreach($users as $user){
if($user->hasdatas()){...}
}
The function i attempt to make check if $user has a data in one of the following method from the user model with a single check :
public function pages(){return $this->hasMany(Page::class, 'author_id');}
public function episodes(){return $this->hasMany(Episode::class, 'author_id');}
public function events(){return $this->hasMany(Event::class, 'author_id');}
public function teasers(){return $this->hasMany(Teaser::class, 'author_id');}
I attempt to make a new method in the user model to check this with a simple call but nothing work. Can someone help me to write this portion of code ?
Hi,
I found a solution but is not very elegant :
public function hasdata(){
$pages = $this->pages()->get()->isEmpty();
$episodes = $this->episodes()->get()->isEmpty();
$events = $this->events()->get()->isEmpty();
$teasers = $this->teasers()->get()->isEmpty();
$articles = $this->articles()->get()->isEmpty();
$flag = [$pages, $episodes, $events, $teasers, $articles];
if(in_array(false, $flag)){return true;}
return false;
}
The quickest approach is an existence query:
select NOT EXISTS (select username from a where username = {$username}) AND NOT EXISTS (select username from b where username = {$username}) AND NOT EXISTS (select username from c where username = {$username});
If your username column is marked as Unique in each table, this should be the most efficient query you will be able to make to perform this operation, and this will outperform a normalized username table in terms of memory usage and, well, virtually any other query that cares about username and another column, as there are no excessive joins. If you've ever been called on to speed up an organization's database, I can assure you that over-normalization is a nightmare. In regards to the advice you've received on normalization in this thread, be wary. It's great for limiting space, or limiting the number of places you have to update data, but you have to weigh that against the maintenance and speed overhead. Take the advice on how to start off an informative essay given to you on this page with a grain of salt.
Get used to running a query analyzer on your queries, if for no other reason than to get in the habit of learning the ramifications of choices when writing queries -- at least until you get your sea legs.
Hi Everyone,
I think to create a view table and call it on ever updated, and maybe even put the whole view table on redis if available, so you will be able to read the table much faster https://blog.tekz.io/laravel-eloquent-how-to-effectively-manage-sql-views/
It is just a idea
Sign in to participate in this thread!
The Laravel portal for problem solving, knowledge sharing and community building.
The community