Hi I just cant wrap my head around One To Many Relations. They seem to never work for me. So i started to work around them or built my own model methods to make them work for me.
This time i thought i should do it right and get this thing cleared out in my head.
So Here is what i got in my Models and Migrations:
//The Migration shema
Schema::create('messages', function(Blueprint $table)
{
$table->increments('id');
$table->text('text');
$table->integer('sender_id')->unsigned()->index();
$table->timestamps();
});
//The onetomany methods in the models
class Message extends \Eloquent {
public function sentBy()
{
return $this->belongsTo('User', 'sender_id', 'id');
}
}
class User extends Eloquent implements UserInterface, RemindableInterface {
...
public function MessagesSent()
{
return $this->hasMany('Message', 'sender_id');
}
}
Now what when i do the following:
$message = Message::create(array('text' => "test"));
$user = User::find(1);
$message->sentFrom()->associate($user);
It seems like the last line does nothing. It creates a table entry but the field "sender_id" is allways 0. No Errors printed what so ever.
On the Other hand it works in the other direction e.g. User::find(1)->messagesSent()->save($message);
Hopefully someone can explain me what im doing wrong here.
Sign in to participate in this thread!
The Laravel portal for problem solving, knowledge sharing and community building.
The community