Laravel投稿サイト構築.81 -いいね機能の実装.1(リレーション)-
今回からはイイネ機能を実装していきます。
目次
テーブル作成
いいねした情報を納めるテーブルを作成。
ユーザIDと投稿ID(返信ID)をキーとする。
-----
php artisan make:migration likes
-----
Schema::create('likes', function (Blueprint $table) {
$table->bigIncrements('id');
$table->bigInteger('thread_id');
$table->bigInteger('reply_id');
$table->bigInteger('user_id');
$table->string('user_ip');
$table->timestamps();
});
-----
ユーザ登録していなくてもイイネできるものとして、
その場合はIPアドレスを'user_ip'にセットする。
モデル作成
-----
php artisan make:model Like -m
-----
リレーション
データを検索する場合に素直に記述しても良いのだが、リレーションを使うと簡単にデータ取得できる。
-----
Userモデル
public function likes()
{
return $this->belongsToMany('App\Models\Post','likes','user_id','post_id')->withTimestamps();
}
public function isLike($postId)
{
return $this->likes()->where('post_id',$postId)->exists();
}
-----
上の例で言うと、UserテーブルからPostテーブルにidとuser_idで結合、さらにPostからlikesテーブルにidとpost_idで結合する、という認識。
今回、非ログインユーザでもイイネできる想定なので、
ユーザマスタからのリレーションにはできない。
かつ、テーマ投稿と返信に対してそれぞれイイネできるので、
Thread(テーマ)とReply(返信)のモデルにそれぞれリレーションを記述した。
Thread.php
-----
// イイネを取得するためのリレーション
public function likes()
{
return $this->belongsToMany('App\Models\Like', 'thread_id')->withTimestamps();
}
public function isLike($thread_id)
{
return $this->likes()->where('thread_id', $thread_id)->exists();
}
-----
Reply.php
-----
// イイネを取得するためのリレーション
public function likes()
{
return $this->belongsToMany('App\Models\Like', 'thread_id')->withTimestamps();
}
public function isLike($thread_id, $reply_id)
{
return $this->likes()
->where([
['thread_id', '=', $thread_id],
['reply_id', '=', $reply_id],
])
->exists();
}
-----
少しずつ進めていきます。
続く。