How to access model hasMany Relation with where condition?

前端 未结 8 1341
迷失自我
迷失自我 2020-12-08 00:02

I created a model Game using a condition / constraint for a relation as follows:

class Game extends Eloquent {
             


        
相关标签:
8条回答
  • 2020-12-08 00:52
     public function outletAmenities()
    {
        return $this->hasMany(OutletAmenities::class,'outlet_id','id')
            ->join('amenity_master','amenity_icon_url','=','image_url')
            ->where('amenity_master.status',1)
            ->where('outlet_amenities.status',1);
    }
    
    0 讨论(0)
  • 2020-12-08 00:53

    Model (App\Post.php):

    /**
     * Get all comments for this post.
     */
    public function comments($published = false)
    {
        $comments = $this->hasMany('App\Comment');
        if($published) $comments->where('published', 1);
    
        return $comments;
    }
    

    Controller (App\Http\Controllers\PostController.php):

    /**
     * Display the specified resource.
     *
     * @param int $id
     * @return \Illuminate\Http\Response
     */
    public function post($id)
    {
        $post = Post::with('comments')
            ->find($id);
    
        return view('posts')->with('post', $post);
    }
    

    Blade template (posts.blade.php):

    {{-- Get all comments--}}
    @foreach ($post->comments as $comment)
        code...
    @endforeach
    
    {{-- Get only published comments--}}
    @foreach ($post->comments(true)->get() as $comment)
        code...
    @endforeach
    
    0 讨论(0)
提交回复
热议问题