Answer the question
In order to leave comments, you need to log in
How to use relationships in Laravel models?
Reading the Laravel documentation. In an Eloquent ORM model, you can define relationships with other models. I can't figure out how to use these relationships. For example, there are two tables:
1. "Object" with fields:
-id(int,primary)
-name(varchar)
-type(int)
2. "Types" with fields:
-id(int,primary)
-type_name(varchar) .
How to set the relation in such a way that when {{$Object->type}} displays not a number, but type_name ?
Answer the question
In order to leave comments, you need to log in
If you have never done this and the database is also just being formed, then follow the recommended conventions for naming tables and columns in the database.
It will be easier like this:
1. "Object" with fields:
-id(int,primary)
-name(varchar)
-type_id(int)
2. "Types" with fields:
-id(int,primary)
-name(varchar) .
Next, in the Object model, write the belongsTo() relationship:
public function type()
{
return $this->belongsTo('App\Type');
}
public function objects(){
return $this->hasMany('App\Object');
}
I don't understand a little.
there is a model:
class Object extends Model {
protected $table = 'object';
public function type(){
return $this->belongsTo('App\Type', 'id');
}
}
class Type extends Model {
protected $table = 'types';
public function type_name(){
return $this->hasMany('App\Object','type','id');
}
}
$obj = Object::find(1);
var_dump($obj->type);
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question