Error 'Array to string conversion' when trying create hasMany relationship model laravel 10

60 Views Asked by At

Here is my code in model Pos ` /**

 * Get all of the details for the Pos

 *

 * @return \Illuminate\Database\Eloquent\Relations\HasMany

 */

public function details(): HasMany

{

    return $this->hasMany(PosDetail::class, ['session_id', 'branch_id', 'strukno']);

}`

And here is my code in model PosDetail

/**
 * Get the pos that owns the PosDetail
 *
 * @return \Illuminate\Database\Eloquent\Relations\BelongsTo
 */
public function pos(): BelongsTo
{
    return $this->belongsTo(Pos::class, ['session_id', 'branch_id', 'strukdate', 'strukno'], ['session_id', 'branch_id', 'strukdate', 'strukno']);
}

What i try to get the data Pos is with this code $post = Pos::all(); return $post; That code is work in laravel 9, but not with laravel 10. Any different syntax between ver. 9 and 10?

1

There are 1 best solutions below

1
Abdulla Nilam On

The hasMany and belongsTo methods in Laravel only support a single foreign key, not an array of keys.

So it should be like this

public function details(): HasMany
{
    return $this->hasMany(PosDetail::class, 'foreign_key_in_pos_details');
}


public function pos(): BelongsTo
{
    return $this->belongsTo(Pos::class, 'foreign_key_in_pos');
}

Ex: if you want to fetch data from pos with the details the.

$pos = Pos::find(1);

foreach ($pos->details as $detail) {
    // access the details here
    echo $detail->field;
}

or

$posWithDetails = Pos::with('details')->get();