I am new to Laravel but started from Laravel 5.0.
I got 2 tables: Doctors
class CreateDoctorsTable extends Migration {
public function up()
{
Schema::create('doctors', function(Blueprint $table)
{
$table->increments('id');
$table->string('url')->unique();
$table->string('name');
$table->text('brief');
$table->text('text');
$table->string('small-photo');
$table->string('large-photo');
$table->softDeletes();
$table->timestamps(); }); }
public function down()
{Schema::drop('doctors'); }
}
And Lesson:
class CreateLessonsTable extends Migration {
public function up()
{
Schema::create('lessons', function(Blueprint $table)
{
$table->increments('id');
$table->string('title');
$table->text('body');
$table->integer('doctor_id');
$table->timestamps();
});
}
public function down()
{
Schema::drop('lessons');
}
}
When i use this:
$doc = Doctor::find(1);
$les = Lesson::whereDoctorId($doc->id)->get();
dd($les);
I got no problems and got 2 records of Lessons.
But if i use
$doc = Doctor::find(1);
dd($doc->lessons());
I got no records at all:
HasMany {#167 ▼ #foreignKey: "lessons.doctor_id" #localKey: "id" #query: Builder {#170 ▶} #parent: Doctor {#168 ▶} #related: Lesson {#160 ▼ #connection: null #table: null #primaryKey: "id" #perPage: 15 +incrementing: true +timestamps: true #attributes: [] #original: [] #relations: [] #hidden: [] #visible: [] #appends: [] #fillable: [] #guarded: array:1 [▶] #dates: [] #casts: [] #touches: [] #observables: [] #with: [] #morphClass: null +exists: false } }
My models are:
class Doctor extends Eloquent {
protected $fillable = ['name', 'url', 'text'];
public function lessons()
{
return $this->hasMany('App\Lesson');
}
}
class Lesson extends Model {
public function doctors()
{
return $this->belongsTo('App\Doctor');
}
}
And for example i got this data:
In Doctors 2 rows with id = 1 and 2 In Lessons 3 rows: id =1 doctor_id = 1 id =2 doctor_id = 1 id =3 doctor_id = 2
I already mad, dont understand why i cant use ORM in a right way? Any help plz...
You have to do i like this:
$doc = Doctor::find(1);
dd($doc->lessons()->get());
Oh really? I just watched some laracasts on 4.1 and done what i've seen there. Tommorow at work i will check this. Thank u a lot.
Thank u a lot, all working now. Was confused laravel 4.1 video, where used just dd($doc->lessons());
Sign in to participate in this thread!
The Laravel portal for problem solving, knowledge sharing and community building.
The community