简体   繁体   中英

Typecast eloquent relation laravel

I have 2 models Tour.php and Itinerary.php in one to many relations:

Tour.php

    public function itinerary()
{
    return $this->hasMany('App\Itinerary', 'tour_id')->orderBy('day', 'asc');
}

Itinerary.php

    public function tour() 
{
    return $this->belongsTo('App\Tour', 'tour_id');
}

The itineraries table consists of the following columns:

id |tour_id | day | detail

The day & detail column are of string type.

I want to print the itineraries of a tour according to ascending order of days.

How do I change the string to integer ?

I'm printing the output with foreach loop in the view:

@foreach($tour->itineraries as $item)
  {{$item->day}}
  {{$item->detail}}
@endforeach

I've tried cast method in model:

    protected $casts = [
    'day' => 'integer',
    ];

And Accessor

public function castDayToInt($value)
{
    return (int)$value;
}

but didn't get the expected result.

Current output of the above code:

  • Day 1
  • Day 11
  • Day 12
  • ....
  • Day 2
  • Day 20
  • Day 21

Expected output

  • Day 1
  • Day 2
  • Day 3
  • .....
  • Day 21

The best solution is change your day type in DB,

If you still need the varchar type, you can do it like this:

public function itineraries()
{
    return $this->hasMany('App\Itinerary', 'tour_id')->orderByRaw('CONVERT(day, UNSIGNED) ASC');
}

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