You have to return the $this->hasMany('Characteristic', 'announcement_id');
You are missing the return.
Frage
I've got two models Announcement:
class Announcement extends Eloquent {
public function characteristics() {
$this->hasMany('Characteristic');
}
}
and Characteristic:
class Characteristic extends Eloquent {
protected $guarded = array();
public static $rules = array();
public function announcement() {
return $this->belongsTo('Announcement');
}
}
There's two tables:
CREATE TABLE characteristics (
id integer PRIMARY KEY AUTOINCREMENT,
title varchar DEFAULT('Количество'),
announcement_id integer,
count integer DEFAULT('0'),
value_name varchar DEFAULT('шт.'),
created_at datetime,
updated_at datetime,
deleted_at datetime
);
and
CREATE TABLE announcements (
id integer PRIMARY KEY AUTOINCREMENT,
title varchar DEFAULT(''),
description varchar DEFAULT(''),
created_at datetime,
updated_at datetime,
deleted_at datetime
);
Both of them are seeded with some test data.
This is my code in routes.php:
Route::get('/', function()
{
$test = Announcement::find(1)->characteristics();
var_dump($test);
});
But I Always got NULL. I can't understand, why...
Lösung
You have to return the $this->hasMany('Characteristic', 'announcement_id');
You are missing the return.
Andere Tipps
Try like this:
public function characteristics() {
return $this->hasMany('Characteristic','announcement_id');
}
public function announcement() {
return return $this->belongsTo('Announcement','announcement_id');
}
function name is the name of your table. First parameter is the model name, second parameter is the matching key name.
Also for good practice, add a foreign key to announcement_id
$table->foreign('announcement_id')->references('id')->on('announcements')->onDelete('cascade');
Also try the query like:
$test = Announcement::find(1)->characteristics; //not a method name