Using accessor to select one result of a related table

Published 1 month ago by Penaf

Having this:

class Especie extends Model
{

    protected $table = 'especies';


    public function multimedia()
    {
        return $this->belongsToMany('App\Multimedia', 'especie_multimedia', 'especie_id', 'multimedia_id')->withPivot('isCover');
    }

Is it possible to do somekind of accessor that gives me the multimedia_id from the pivotal table where isCover = 1 ? Or is there a bettter/faster way to do this?


    protected $appends = ['nome_total'];

    public function getCoverAttribute()
    {

    return $multimedia_id;

    }
Best Answer (As Selected By Penaf)
Cronix

What about this? Order by isCover and grab the first instead of 2 separate queries.

$capa = $this->multimedia()
     ->sortBy('isCover', 'desc')
     ->pluck('multimedia_id')
     ->first();
if (!isset($capa)) {
    $capa = 7506;
}
Penaf

Just some more info...

With this I'm getting 15157 when the result should be 9984:

    public function getCapaAttribute()
    {
        $capa = '';

        if (isset($this->multimedia)) {
            foreach ($this->multimedia as $k => $v) {
                $capa = $v->id;
                if ($v->isCover === 1) {
                    $capa = $v->id;
                    break;
                }
            }
        } else {
            $capa = 7506;
        }

         return $capa;
    }

What comes from the database is:

especie_id | multimedia_id | isCover
888 | 9984 | 1
888 | 9985 | 0
888 | 15154 | 0
888 | 15155 | 0
888 | 15156 | 0
888 | 15157 | 0
Snapey
Snapey
1 month ago (1,040,245 XP)

what is wrong with using where() ?

Penaf

I think I can't use it due to this:

There are 3 possibilities:

  • No cover photo defined, no photos at all ... output must be 7506
  • No cover photo defined, photos exist ... output can be any multimedia id
  • Cover photo defined ... output is the corresponding id.
Penaf

Like so?

    public function getCapaAttribute()
    {

        $capa = $this->multimedia()
            ->where('isCover', '=', 1)
            ->pluck('multimedia_id')
            ->first();

        if (!isset($capa)) {
            $capa = $this->multimedia()
                ->where('isCover', '=', 0)
                ->pluck('multimedia_id')
                ->first();
        }

        if (!isset($capa)) {
            $capa = 7506;
        }

   }

Have a feeling the code could be much more simpler and efficient ... but it's working.

Cronix
Cronix
1 month ago (794,690 XP)

What about this? Order by isCover and grab the first instead of 2 separate queries.

$capa = $this->multimedia()
     ->sortBy('isCover', 'desc')
     ->pluck('multimedia_id')
     ->first();
if (!isset($capa)) {
    $capa = 7506;
}
Penaf

Way better!! Thanks mate!

Please sign in or create an account to participate in this conversation.