Support the ongoing development of Laravel.io →
Eloquent Architecture
Last updated 1 year ago.
0

this is how I made CRUD with laravel, still maybe exists a better approach

// models/Post.php
class Post extends Eloquent {
	
	protected $table = 'posts';
	
	public function comments() {
		return $this->hasMany( 'Comments' );
	}
	
}

// models/Comment.php
class Comment extends Eloquent {
	
	protected $table = 'comments';
	
	public function post() {
		return $this->belongsTo( 'Post' );
	}
}

// for create
$post = new Post();
$post->data = $data;
$post->save(); // will create a record in posts table

$comments = new Comments();
$comments->post()->associate( $post ); // grab the post id
$comments->data = $data;
$comments->save(); // will create a record in comments table with the correct post_id

// for update
$post = Post::find( $id );
$post->data = $data;
$post->comments->data = $data;
$post->push(); // will update post and coment records

// for delete (you must also setup the cacasde on delete in your schema definition on comments table to make this works)
$post->delete();

for transactions check here: http://laravel.com/docs/database#database-transactions

Last updated 1 year ago.
0

There is no equivalent to saveAll in Laravel. The best practice is handle relationship cascades as events in your models:

http://laravel.com/docs/eloquent#model-events

That is, when you save your model, you listen for either the saving or saved event, at which point, you then apply whatever child / parent saving strategy you need (either save, associate, attach, detatch or sync).

That said, depending on the complexity of your relationship structure, this might be a bit cumbersome to implement efficiently and without triggering errors, which is why I suspect we don't currently have something like a saveAll() method available.

Last updated 1 year ago.
0

GRAgmLauncher said:

There is no equivalent to saveAll in Laravel. The best practice is handle relationship cascades as events in your models:

http://laravel.com/docs/eloquent#model-events

That is, when you save your model, you listen for either the saving or saved event, at which point, you then apply whatever child / parent saving strategy you need (either save, associate, attach, detatch or sync).

That said, depending on the complexity of your relationship structure, this might be a bit cumbersome to implement efficiently and without triggering errors, which is why I suspect we don't currently have something like a saveAll() method available.

Does it mean we have to impletment a DB transaction by ourself ?

Last updated 1 year ago.
0

Sign in to participate in this thread!

Eventy

Your banner here too?

edsuna edsuna Joined 5 Mar 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.

© 2024 Laravel.io - All rights reserved.