CSV Export using a hasMany

I am trying to create an export of orders which has many items. What I would like is to put the items in one column separated by a comma. I am using the following setup:

<?php namespace Jlh\Equipment\Models;
class OrderExport extends \Backend\Models\ExportModel
{

	public $table = 'jlh_equipment_orders';

	public $belongsTo = [
		'league' => \Jlh\Player\Models\League::class
	];

	public $hasMany = [
		'items' => \Jlh\Equipment\Models\Item::class
	];

	protected $appends = [
		'league_name',
		'items'
	];

	public function exportData($columns, $sessionKey = null)
	{

		$query = self::make();
		return $query->get()->toArray();

	}

	public function getLeagueNameAttribute()
	{
		if (isset($this->league->name))
		{
			return $this->league->name;
		} else {
			return '';
		}
	}

	public function getItemsAttribute()
	{
		$items = Item::where('order_id',$this->id)->get();
		foreach ($items as $item)
		{
			$result = $item->name;
			return $result;
		}
	}

}
?>

The function getItemsAttribute is only pulling one item, even if the order has several.

Any help is appreciated.
Thanks.

you are returning the first $item->name.

If you want to return item1_name, item2_name, etc…you can try this:

public function getItemsAttribute()
    {
        $items = Item::where('order_id', $this->id)->get();
        $result = [];

        foreach ($items as $item) {
            $result[] = $item->name;
        }

        if (count($result) === 1) {
            return $result[0]; // Return the single item without a comma
        }

        // Use implode to concatenate the names with commas
        return implode(', ', $result);
    }
1 Like

Thanks so much - it worked. Have a great weekend.

1 Like