質問をすることでしか得られない、回答やアドバイスがある。

15分調べてもわからないことは、質問しよう!

新規登録して質問してみよう
ただいま回答率
85.48%
COUNT

COUNT は、広く使用されているSQLの関数です。COUNT関数は、行数、もしくは配列のエンティティの数をカウントします。

Laravel

LaravelとはTaylor Otwellによって開発された、オープンソースなPHPフレームワークです。Laravelはシンプルで表現的なシンタックスを持ち合わせており、ウェブアプリケーション開発の手助けをしてくれます。

PHP

PHPは、Webサイト構築に特化して開発されたプログラミング言語です。大きな特徴のひとつは、HTMLに直接プログラムを埋め込むことができるという点です。PHPを用いることで、HTMLを動的コンテンツとして出力できます。HTMLがそのままブラウザに表示されるのに対し、PHPプログラムはサーバ側で実行された結果がブラウザに表示されるため、PHPスクリプトは「サーバサイドスクリプト」と呼ばれています。

Q&A

解決済

1回答

1597閲覧

laravel countが0になって返ってくる

hina0823

総合スコア15

COUNT

COUNT は、広く使用されているSQLの関数です。COUNT関数は、行数、もしくは配列のエンティティの数をカウントします。

Laravel

LaravelとはTaylor Otwellによって開発された、オープンソースなPHPフレームワークです。Laravelはシンプルで表現的なシンタックスを持ち合わせており、ウェブアプリケーション開発の手助けをしてくれます。

PHP

PHPは、Webサイト構築に特化して開発されたプログラミング言語です。大きな特徴のひとつは、HTMLに直接プログラムを埋め込むことができるという点です。PHPを用いることで、HTMLを動的コンテンツとして出力できます。HTMLがそのままブラウザに表示されるのに対し、PHPプログラムはサーバ側で実行された結果がブラウザに表示されるため、PHPスクリプトは「サーバサイドスクリプト」と呼ばれています。

0グッド

0クリップ

投稿2020/10/11 11:07

前提・実現したいこと

laravel初心者です。Twitter風のアプリケーションを勉強していて、フォロー、フォロー解除の実装ができ
フォローしているユーザーの人数、フォローされいているユーザーの人数の表示をcountを使ってしようとしています。

発生している問題

実際にフォローはしていも"0"で表示されます。

該当ソースコード

FollowsController

php

1namespace App\Http\Controllers; 2 3use Illuminate\Http\Request; 4use Illuminate\Support\Facades\Auth; 5use Illuminate\Support\Facades\DB; 6use App\User; 7use App\Post; 8use App\Follow; 9 10class FollowsController extends Controller 11{ 12 13public function show(User $user, Follow $follow) 14 { 15 $login_user = auth()->user(); 16 $is_following = $login_user->isFollowing($user->id); 17 $is_followed = $login_user->isFollowed($user->id); 18 $follow_count = $follow->getFollowCount($user->id); 19 $follower_count = $follow->getFollowerCount($user->id); 20 21 return view('users.show', [ 22 'user' => $user, 23 'is_following' => $is_following, 24 'is_followed' => $is_followed, 25 'follow_count' => $follow_count, 26 'follower_count' => $follower_count 27 ]); 28 } 29}

Userモデル

php

1namespace App; 2 3use Illuminate\Notifications\Notifiable; 4use Illuminate\Foundation\Auth\User as Authenticatable; 5 6class User extends Authenticatable 7{ 8 use Notifiable; 9 10 /** 11 * The attributes that are mass assignable. 12 * 13 * @var array 14 */ 15 protected $fillable = [ 16 'username', 'mail', 'password', 17 ]; 18 19 /** 20 * The attributes that should be hidden for arrays. 21 * 22 * @var array 23 */ 24 protected $hidden = [ 25 'password', 'remember_token', 26 ]; 27 28 public function followers() 29 { 30 return $this->belongsToMany(User::class, 'follows', 'followed_id', 'following_id'); 31 } 32 33 public function follows() 34 { 35 return $this->belongsToMany(User::class, 'follows', 'following_id', 'followed_id'); 36 } 37 38 public function isFollowing($user_id) 39 { 40 return (boolean) $this->follows()->where('followed_id', $user_id)->exists(); 41 } 42 43 public function isFollowed($user_id) 44 { 45 return (boolean) $this->followers()->where('following_id', $user_id)->exists(); 46 } 47 48}

Followモデル

php

1namespace App; 2 3use Illuminate\Database\Eloquent\Model; 4 5class Follow extends Model 6{ 7 8 protected $primaryKey = [ 9 'following_id', 'followed_id' 10 ]; 11 12 protected $fillable = [ 13 'following_id', 'followed_id' 14 ]; 15 16 public function getFollowCount($user_id) 17 { 18 return $this->where('following_id', $user_id)->count(); 19 } 20 21 public function getFollowerCount($user_id) 22 { 23 return $this->where('followed_id', $user_id)->count(); 24 } 25 26}

Route

php

1Route::group(['middleware' => 'auth'], function() { 2Route::get('/show','FollowsController@show'); 3});

viewはフォロー数が{{ $follow_count }}
フォロワー数が{{ $follower_count }}で表示しております。

バージョン

laravel 5.5.48
php 7.4.5
homestead

また0で返ってくるということは該当するものに値が入っていないという認識で間違いないでしょうか?
ご教授の程よろしくお願い致します。

気になる質問をクリップする

クリップした質問は、後からいつでもMYページで確認できます。

またクリップした質問に回答があった際、通知やメールを受け取ることができます。

バッドをするには、ログインかつ

こちらの条件を満たす必要があります。

guest

回答1

0

ベストアンサー

php

1<?php 2 3namespace App; 4 5use Illuminate\Database\Eloquent\Relations\BelongsToMany; 6use Illuminate\Foundation\Auth\User as Authenticatable; 7use Illuminate\Notifications\Notifiable; 8 9/** 10 * App\User 11 * 12 * @property int $id 13 * @property string $name 14 * @property string $email 15 * @property \Illuminate\Support\Carbon|null $email_verified_at 16 * @property string $password 17 * @property string|null $remember_token 18 * @property \Illuminate\Support\Carbon|null $created_at 19 * @property \Illuminate\Support\Carbon|null $updated_at 20 * @property-read \Illuminate\Database\Eloquent\Collection|User[] $followees 21 * @property-read int|null $followees_count 22 * @property-read \Illuminate\Database\Eloquent\Collection|User[] $followers 23 * @property-read int|null $followers_count 24 * @property-read \Illuminate\Notifications\DatabaseNotificationCollection|\Illuminate\Notifications\DatabaseNotification[] $notifications 25 * @property-read int|null $notifications_count 26 * @method static \Illuminate\Database\Eloquent\Builder|User newModelQuery() 27 * @method static \Illuminate\Database\Eloquent\Builder|User newQuery() 28 * @method static \Illuminate\Database\Eloquent\Builder|User query() 29 * @method static \Illuminate\Database\Eloquent\Builder|User whereCreatedAt($value) 30 * @method static \Illuminate\Database\Eloquent\Builder|User whereEmail($value) 31 * @method static \Illuminate\Database\Eloquent\Builder|User whereEmailVerifiedAt($value) 32 * @method static \Illuminate\Database\Eloquent\Builder|User whereId($value) 33 * @method static \Illuminate\Database\Eloquent\Builder|User whereName($value) 34 * @method static \Illuminate\Database\Eloquent\Builder|User wherePassword($value) 35 * @method static \Illuminate\Database\Eloquent\Builder|User whereRememberToken($value) 36 * @method static \Illuminate\Database\Eloquent\Builder|User whereUpdatedAt($value) 37 * @mixin \Eloquent 38 */ 39class User extends Authenticatable 40{ 41 use Notifiable; 42 43 /** 44 * The attributes that are mass assignable. 45 * 46 * @var array 47 */ 48 protected $fillable = [ 49 'name', 'email', 'password', 50 ]; 51 52 /** 53 * The attributes that should be hidden for arrays. 54 * 55 * @var array 56 */ 57 protected $hidden = [ 58 'password', 'remember_token', 59 ]; 60 61 /** 62 * The attributes that should be cast to native types. 63 * 64 * @var array 65 */ 66 protected $casts = [ 67 'email_verified_at' => 'datetime', 68 ]; 69 70 /** 71 * すでにフォーロしているかどうかを判定する 72 * 73 * @param User $followee 74 * @return bool 75 */ 76 public function hasFollowee(User $followee): bool 77 { 78 return $this->followees->pluck('id')->contains($followee->id); 79 } 80 81 /** 82 * 自分がフォローしているユーザー 83 * 84 * @return BelongsToMany 85 */ 86 public function followees(): BelongsToMany 87 { 88 return $this->belongsToMany(self::class, 'follow', 'follower_id', 'followee_id'); 89 } 90 91 /** 92 * 自分をフォローしているユーザー 93 * 94 * @return BelongsToMany 95 */ 96 public function followers(): BelongsToMany 97 { 98 return $this->belongsToMany(self::class, 'follow', 'followee_id', 'follower_id'); 99 } 100 101 /** 102 * ミュートしているユーザー 103 * 104 * @return BelongsToMany 105 */ 106 public function muting(): BelongsToMany 107 { 108 return $this->belongsToMany(self::class, 'mute', 'user_id', 'muted_id'); 109 } 110 111 /** 112 * ブロックしているユーザー 113 * 114 * @return BelongsToMany 115 */ 116 public function blocked(): BelongsToMany 117 { 118 return $this->belongsToMany(self::class, 'block', 'user_id', 'blocked_id'); 119 } 120}

このように定義するだけで、
コントローラーから、

php

1$user = User::find(1); 2$followers_count = $user->followers_count; 3dd($followers_count);

と値が取れます。

中間テーブルのモデル、「Followモデル」は作成する必要はありません。

投稿2020/10/11 13:16

phper.k

総合スコア3923

バッドをするには、ログインかつ

こちらの条件を満たす必要があります。

phper.k

2020/10/11 13:17

テーブル名やカラム名はご自身の環境に合わせて変更してください。
hina0823

2020/10/12 12:30 編集

ご回答ありがとうございます。 $user = User::find(1); $followers_count = $user->followers_count; こちらのfollowers_countはどこの値を受け取っているのでしょうか。
phper.k

2020/10/12 13:41 編集

> こちらのfollowers_countはどこの値を受け取っているのでしょうか。 質問の意味がちょっとわからないのですが、どういうことですか? https://readouble.com/laravel/5.8/ja/eloquent-relationships.html 「関連するモデルのカウント」の項目にあるように、Laravel によって自動的に設定される値です。
hina0823

2020/10/12 14:00

ご回答ありがとうございます。 followers_count;はモデルのどこから取得している値なのかが、不明だった為質問させていただきましたが、ご提示いただいたURLを確認したところ理解致しました。 また、理解したうえでご教授いただいた記述を試したところ、"null" で値が返ってきました。考えられる原因はデータベースにあると推測してよろしいでしょうか。
phper.k

2020/10/12 14:20

> 考えられる原因はデータベースにあると推測してよろしいでしょうか。 単にデータが入っていないのか、リレーションが間違っているのでは?
hina0823

2020/10/12 14:44

データベース上でデータは確認できるので、多分ですがリレーションの間違いだと思います。大変参考になりました。ありがとうございます。
guest

あなたの回答

tips

太字

斜体

打ち消し線

見出し

引用テキストの挿入

コードの挿入

リンクの挿入

リストの挿入

番号リストの挿入

表の挿入

水平線の挿入

プレビュー

15分調べてもわからないことは
teratailで質問しよう!

ただいまの回答率
85.48%

質問をまとめることで
思考を整理して素早く解決

テンプレート機能で
簡単に質問をまとめる

質問する

関連した質問