Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

vincent15000's avatar

Query builder => is it possible to mix with() and addSelect() methods ?

Hello,

I am trying to do this in a Livewire component.

$alertes = Alerte::
    with('salarie')
    ->with('formation')
    ->join('formations', 'formations.id', '=', 'alertes.formation_id')
    ->addSelect(DB::raw('date_add(formations.date_fin, interval formations.duree_validite month) as date_recyclage'))
    ->where('formations.entreprise_id', $this->entreprise_id)
    ->when($this->traitee, function ($query) {
        $query->where('traitee', $this->traitee);
    })
    ->orderByRaw($this->critere_tri, $this->asc ? 'asc' : 'desc')
    ->paginate($this->nombre_par_page);

But when I try to display $alerte->formation->intitule, it doesn't work (intitule not found). I had a look at the query result with dd. I have only one field : date_recyclage.

Why do I have only one field whereas the beginning of my query has to retrieve the alerte with salarie and formation ?

What's wrong in my code ? Do you have any idea ?

Thanks for your help.

Vincent

0 likes
5 replies
MichalOravec's avatar
Level 75

Instead of

->addSelect(DB::raw('date_add(formations.date_fin, interval formations.duree_validite month) as date_recyclage'))

use

->selectRaw('alertes.*, date_add(formations.date_fin, interval formations.duree_validite month) as date_recyclage')

Of course use your table name alertes

SilenceBringer's avatar

@vincent15000 from official docs (scroll down a little to addSelect section):

If you already have a query builder instance and you wish to add a column to its existing select clause, you may use the addSelect method:

But - you don't have select. So, it contains 1 value only.

By the way - your query looks wrong to my. you try to use eager loading by using with, but next line you join this table formation again. Possible something like that will make more sense

$alertes = Alerte::
    with([
        'salarie',
        'formation' => function ($query) {
            $query->select(['*', Db::raw('date_add(date_fin, interval duree_validite month) as date_recyclage')]);
        })
    ])
    ->whereHas('formation' => function ($query) {
        $query->where('entreprise_id', $this->entreprise_id)
    })
    ->when($this->traitee, function ($query) {
        $query->where('traitee', $this->traitee);
    })
    ->orderByRaw($this->critere_tri, $this->asc ? 'asc' : 'desc')
    ->paginate($this->nombre_par_page);
MichalOravec's avatar

Nothing wrong with his query.whereHas is much slower then join and I guess he uses date_recyclage for ordering and in that case join is necessary.

I don't use whereHas in big projects.

1 like
vincent15000's avatar

That's it ! I effectively use date_recyclage for ordering ... and also for filtering the alerts to display.

Please or to participate in this conversation.