D
D
DieZz2015-03-14 19:00:03
Laravel
DieZz, 2015-03-14 19:00:03

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

3 answer(s)
S
Sergey Gladkovskiy, 2015-03-17
@DieZz

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');
}

And in Type - the hasMany connection:
public function objects(){
    	return $this->hasMany('App\Object');
  }

And everything should work.
INT to you is produced as you communication and a column named identically. It is not the connection that is returned, but the content of the column of the same name...

M
Max, 2015-03-14
@zenwalker

laravel.com/docs/5.0/eloquent#relationships

D
DieZz, 2015-03-14
@DieZz

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);

Result: string(1) "1" Let me rephrase
the question a bit: how to use Eloquent ORM to execute a query of this kind:
SELECT id,name, (SELECT type_name FROM Types WHERE id=object.type) as type FROM object where id=1

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question