Support the ongoing development of Laravel.io →
posted 10 years ago
Eloquent

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.

Last updated 3 years ago.
0

Sign in to participate in this thread!

PHPverse

Your banner here too?

meneman meneman Joined 7 May 2014

Moderators

We'd like to thank these amazing companies for supporting us

Your logo here?

Laravel.io

The Laravel portal for problem solving, knowledge sharing and community building.

© 2025 Laravel.io - All rights reserved.