Laravel 插入数据

2018-11-03  本文已影响0人  AnnaJIAN

写一个Comment表插入数据的例子
Comment表和Post表用post_id关联

CommentsController.php
use App\Comment;
...
public function store(Post $post)
{
    request()->validate([
        'comment' => 'min:2|max:255'
    ]);
    $comment = new Comment;
    $comment->body = request('comment');
    $comment->post_id = $post->id;
    $comment->save();

    return redirect('/posts/' . request('post_id'));
}
CommentsController.php
use App\Comment;
...
public function store(Post $post)
{
    request()->validate([
        'comment' => 'min:2|max:255'
    ]);
    Comment::create([
        'body' => request('comment'),
        'post_id' => $post->id
    ]);
    return back();
}

以上情况是每次存数据,都要new Comment...改进一下代码, 把存comment的业务逻辑放入Post model 里面。

namespace App\Http\Controllers;
use App\Post;
class CommentsController extends Controller
{
    public function store(Post $post)
    {
        $post->addComment(request());
        return back();
    }
}
App\Post.php
use App\Comment;

class Post extends Model
{
    protected $fillable = ['title', 'body', 'user_id'];

    public function addComment($request)
    {
        $request->validate([
            'comment' => 'min:2|max:255'
        ]);
        Comment::create([
            'body' => $request->comment,
            'post_id' => $this->id,
            'user_id' => $this->user_id
        ]);
    }

为啥不把存入comment的业务逻辑放入comment model里面呢?
我认为comment和post有绑定关系,一个post底下有N个comment,存入comment应该算是一个post在存入comment,而不是一个单独的孤立的存入操作,所以要放在post下面。

比如在post里面写入关联关系的方法

public function comments()
{
    return $this->hasMany(Comment::class);
}

post取相关的comment直接用 $post->comments就行了。hasMany方法把Post表和Comments表关联起来了。
说明:Laravel有自己的关联规则。Model的class类名必须和表名一致,或多少一个s。
调用的话,实例话的model类调用表名,$post->comments。

具体和以下代码有关。

/**
 * Create a new model instance for a related model.
 *
 * @param  string  $class
 * @return mixed
 */
protected function newRelatedInstance($class)
{
    return tap(new $class, function ($instance) {
        if (! $instance->getConnectionName()) {
            $instance->setConnection($this->connection);
        }
    });
}

需要进一步研究

上一篇 下一篇

猜你喜欢

热点阅读