Connecting two tables in mysql

I have two tables in my database - vnames and vtypes
vtypes have a name field and an id field, vnames have an id field, a name field and a vtypes_id field, which is the field associated with the foreign key. It is associated with the id field in views.

I have Vname and Vtype models -

Vname

<?php namespace App; use Illuminate\Database\Eloquent\Model; class Vname extends Model { public function vtype() { return $this->belongsTo('App\Vtype'); } } 

VType

 <?php namespace App; use Illuminate\Database\Eloquent\Model; class Vtype extends Model { public function vname() { return $this->hasMany('App\Vtype'); } } 

When I delete any column in the vtype table, I want to delete all the vname columns associated with it. I found a solution like this -

 public function vtypeDestroy($id) { $vtype = Vtype::find($id); $vtype->vname()->detach(); $vtype->delete(); Session::flash('success', 'The vtype was successfully deleted'); return redirect('/vtypes'); } 

but when I run this function, I get this error: Call to undefined method Illuminate\Database\Query\Builder::detach()

How can i fix this?

And when I want to get the vtype name from vname, I cannot do this. I tried like this

 @foreach ($vnames as $vname) {{ $vname->vtype()->name }} @endforeach 

in view

But I have such an error - Undefined property: Illuminate\Database\Eloquent\Relations\BelongsTo::$name

Please tell me how to fix these two problems that I am facing right now.

+5
source share
2 answers

Your attitude should be like this:

Model Vname

 class Vname extends Model { public function vtype() { return $this->belongsTo('App\Vtype', 'vtypes_id', 'id'); } } 

VType

 class Vtype extends Model { public function vname() { return $this->hasMany('App\Vname', 'vtypes_id', 'id'); } } 

Then you can use the delete method to delete relationships like:

 $vtype = Vtype::find($id); $vtype->vname()->delete(); $vtype->delete(); 

And, in your opinion, it should be like:

 @foreach ($vnames as $vname) {{ $vname->vtype->name }} @endforeach 

Docs

+2
source

Please, use...

 $vtype->vname()->delete(); 

instead of $vtype->vname()->detach(); ... The problem is solved! To access it vname->vtype() you can use the dissociate() method ... which sets vtype_id to null in the vname table. More explanation here

Disconnecting is used for belongsToMany() - belongsToMany() ... yours hasMany() - belongsTo() .

In addition, instead of {{ $vname->vtype()->name }}

do

 @foreach ($vnames as $vname) {{ $vname->vtype->name }} @endforeach 

The reason for this is ... when you put the brackets in front of the relation name, it calls the query builder ... But here you need a model ... So $vname->vtype will give you the Vtype Model , and $vname->vtype() will provide you request builder.

+2
source

Source: https://habr.com/ru/post/1261616/


All Articles