Hi, I have 1 little doubt, I am making a little blog, where i want all blog to get auto-update whenever there is change in username. Below are my tables :-
** User Table **
Schema::create('users', function(Blueprint $table)
{
$table->increments('id');
$table->string('username')->unique();
$table->string('email')->unique();
$table->string('password');
$table->string('first_name');
$table->string('last_name');
$table->timestamps();
});
** Article Table **
Schema::create('blog', function(Blueprint $table)
{
$table->increments('id');
$table->string('username');
$table->string('title');
$table->longtext('message');
$table->foreign('username')->references('username')->on('users')->onUpdate('cascade')->onDelete('cascade');
$table->timestamps();
});
My doubt is, Am i doing Schem in correct way. I mean, Will above my code makes work as i want it to. Whenever username will change in user table, blog username will auto get updated or deleted , whatever be the condition. [ In Short if i update user table, will it auto update blog table with modified username. ? ]
Or , should i move my foreign
column line to user
table ??
Is my code correct, or do i need to fix it ??
Thanks
I would go this way
First please!.... Name the model SAME as the table name.
I would not create username field again in blogs table.
So...
Blogs Table (Blog model)
Schema::create('blogs', function(Blueprint $table)
{
$table->increments('id');
$table->integer('user_id')->unsigned()->index();
$table->foreign('user_id')->references('id')->on('users')->onDelete('cascade');
$table->string('title');
$table->longtext('message');
$table->timestamps();
});
In your User model
public function blog()
{
return $this->hasMany('Blog')
}
In your Blog model
public function user()
{
return $this->belongsTo('User')
}
Now the Blog is in relation to User, so whenever User change the name, you can access the username for the blog by
{{ $blog->user->username}}
@Torchsk, It's not about fetching bro. I am asking about update, ? i.e, if i update user table, will it auto update blog table with modified username. ?
No it won't. As TorchSK mentioned, you should use the users ID rather than their username. From what you have said, a user seems to be able to change their username, where as the users ID will never change, so use that to refer to a user in other tables.
Well yeah.. i was bit in a hurry so I did not explain myself...
But as shabushabu said, it is better to reference to user ID instead of username, while ID never change...
If there is not a special reason why to have username attribute also on Blog, it is better no to.
You can always use "User's username" as "Blog's username" as each Blog belongs to user.
Sign in to participate in this thread!
The Laravel portal for problem solving, knowledge sharing and community building.
The community