简体   繁体   中英

Eloquent ORM query refactoring

I am using eloquent ORM in laravel to write a query that looks a bit complex.

Can somebody help me write this query using eloquent with using models for game_sentences and sentence_progress

The query

select * from d0372341.game_sentences a left join (select * from d0372341.sentence_progress where user_id='b86edcb74928bb1818c22e586aeff0a99060aca7') b on a.id=b.sentence_id where a.topic='abortion' and b.user_id is null order By rand()
select * from d0372341.game_sentences a 
left join (
select * from d0372341.sentence_progress 
where user_id='b86edcb74928bb1818c22e586aeff0a99060aca7'
) b 
on a.id=b.sentence_id 
where a.topic='abortion' 
and b.user_id is null order By rand()

You can use models relation but here your query is based on the curent User like Auth::user() or a random user (with an id)?

In both way you can do a query in your models with an ManyToMany relation and pivot:

# In User
# function gameSentences(): belongsToMany
return $this->belongsToMany(GameSentence::class)->using(SentenceProgress::class);;

# In GameSentence
# function users(): belongsToMany
return $this->belongsToMany(User::class)->using(SentenceProgress::class);;

# the functions you may needs in SentenceProgress pivot
# don't forget to extends with Pivot instead of Model and match the correct table in bdd

# In GameSentences
# static funtion getGameSentencesByTopic(User $user, $topic)
$user->gameSentences
     ->whereTopic($topic);

# Use pivot ->pivot(...), ->wherePivot() if you want to filter with the intermediate table
In the both case SentenceProgress is load in GameSentence and User

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM