V
V
Vitaly2019-05-14 09:44:32
Laravel
Vitaly, 2019-05-14 09:44:32

Error with partial duplication?

Good afternoon. Faced such a situation.
There is a table of cars in which there is a brand id and a client id and the name of the car itself. Everything is saved to the database perfectly, but when displaying all this goodness, if 2 lines in the database have the same brand and client id, when trying to get the brand name and client name.
migration

Schema::create('cars', function (Blueprint $table) {
    $table->increments('id');
    $table->string('title');
    $table->unsignedInteger('model_id');
    $table->foreign('model_id')->references('id')->on('model')->onDelete('cascade');
    $table->unsignedInteger('user_id');
    $table->foreign('user_id')->references('id')->on('users')->onDelete('cascade');
    $table->timestamps();
    });

Model
protected $fillable = ['title',  'user_id', 'car_id'];

public function users()
{
    return $this->hasMany(User::class, 'id');
}

public function models(){
    return $this->hasMany(Model::class, 'id');
}

Controller
public function store(Request $request)
{
    $car = Car::create([
        'title'             =>  $request->title,
        'user_id'           =>  $request->user,
        'model_id'     =>  $request->publisher
    ]);

    return redirect(route('all_cars'));
}

view
@foreach($cars as $index => $car)
    <tr scope="row">
        <td>{{ $index + 1 }}</td>
        <td>{{ $car->title }}</td>
        <td>{{ $car->models->first()->title }}</td>
        <td>{{ $car->users->first()->name }}</td>
    </tr>
@endforeach

Base
id | title | model_id | user_id
1 | a | 1 | 1
2 | b | 2 | 2
3 | c | 3 | 3
4 | d | 3 | 3
As a result, all brands and user names are displayed up to 3 on the fourth I get null

Answer the question

In order to leave comments, you need to log in

1 answer(s)
D
dk-web, 2019-05-14
@kat-vetal

offhand, it seems to me that you made a little mistake with car_id (you have it in fillable) and model_id
and keys in the model

public function users(){
    return $this->hasMany('App\User', 'user_id','id');
}

this is how it should be - first the foreign key comes.
well, with models, respectively

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question