実現したいこと
1.userテーブルとpostテーブルについて、一対多のリレーションと多対多(acceptsメソッド)のリレーションを定義している。
2.中間テーブルのpost_userテーブルにacceptというカラム(boolean)を設定し、それがtrueの人数をカウントしたい。
発生している問題・分からないこと
urlのidからpostを$postbodyとして取得し、bladeで $postbody->accepts->pivot->where('accept',true)->count() としてacceptカラムがtrueの人数を集計しようとすると、Property [pivot] does not exist on this collection instance. のエラーが出てしまう。
該当のソースコード
namespace App\Http\Controllers; use Illuminate\Http\Request; use App\Models\Post; use App\Models\User; class ApprovalController extends Controller { public function index(Post $post,Request $request){ $id=$request->id; return view('approval.index')->with([ 'postbody'=>$post->postbody($id), ]); } }
namespace App\Models; use Illuminate\Database\Eloquent\Factories\HasFactory; use Illuminate\Database\Eloquent\Model; use Illuminate\Http\Request; class Post extends Model { public function user(){ return $this->belongsTo(User::class); } public function accepts(){ return $this->belongsToMany(User::class)->withPivot('accept'); } public function postbody($id){ $postbody=null; if(!empty($id)){ $postbody=Post::find($id); } return $postbody; } }
namespace App\Models; use Illuminate\Database\Eloquent\Factories\HasFactory; use Illuminate\Foundation\Auth\User as Authenticatable; use Illuminate\Notifications\Notifiable; use Laravel\Sanctum\HasApiTokens; class User extends Authenticatable { public function posts(){ return $this->hasMany(Post::class); } public function accepts(){ return $this->belongsToMany(Post::class); } }
post_user_table public function up() { Schema::create('post_user', function (Blueprint $table) { $table->id(); $table->integer('post_id'); $table->integer('user_id'); $table->boolean('accept')->default(false); }); }
approval\index.blade.php <p>承認状況{{$postbody->accepts->pivot->where('accept',true)->count()}}/{{$postbody->accepts->count()}}</p>
試したこと・調べたこと
- teratailやGoogle等で検索した
- ソースコードを自分なりに変更した
- 知人に聞いた
- その他
上記の詳細・結果
もともと $postbody->accepts->where('accept',true)->count() としていたところ、公式ドキュメントを読み、pivotを使えばいけるかもと思ったがダメ。
公式や個人ブログではforeachで要素を取り出す方法ばかり紹介されており、自分の基礎部分の理解が足りないこともあって詰みました。
補足
コードの不要と思われる部分は省いています。不足がある場合はご指摘ください。

回答1件
あなたの回答
tips
プレビュー
バッドをするには、ログインかつ
こちらの条件を満たす必要があります。