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
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.
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 ?
Sign in to participate in this thread!
The Laravel portal for problem solving, knowledge sharing and community building.
The community