Laravel। संबंध के साथ मॉडल में गुंजाइश () का उपयोग करें


102

मेरे पास दो संबंधित मॉडल हैं: Categoryऔर Post।

Postमॉडल एक है publishedगुंजाइश (विधि scopePublished())।

जब मैं सभी श्रेणियों को उस दायरे में लाने की कोशिश करता हूं:

$categories = Category::with('posts')->published()->get();

मुझे एक त्रुटि मिली:

अपरिभाषित विधि से कॉल करें published()

वर्ग:

class Category extends \Eloquent
{
    public function posts()
    {
        return $this->HasMany('Post');
    }
}

पद:

class Post extends \Eloquent
{
   public function category()
   {
       return $this->belongsTo('Category');
   }


   public function scopePublished($query)
   {
       return $query->where('published', 1);
   }

}

जवाबों:


179

आप इसे इनलाइन कर सकते हैं:

$categories = Category::with(['posts' => function ($q) {
  $q->published();
}])->get();

आप किसी संबंध को भी परिभाषित कर सकते हैं:

public function postsPublished()
{
   return $this->hasMany('Post')->published();
   // or this way:
   // return $this->posts()->published();
}

और फिर:

//all posts
$category->posts;

// published only
$category->postsPublished;

// eager loading
$categories->with('postsPublished')->get();

6
संयोग से, यदि आप केवल Category::whereHas('posts', function ($q) { $q->published(); })->get();
— वही

2
@tptcat हाँ। Category::has('postsPublished')इस मामले में भी हो सकता है
— Jarek Tkaczyk

स्वच्छ प्रश्न, स्वच्छ उत्तर!
— मोजतबा एचएन
हमारी साइट का प्रयोग करके, आप स्वीकार करते हैं कि आपने हमारी Cookie Policy और निजता नीति को पढ़ और समझा लिया है।
Licensed under cc by-sa 3.0 with attribution required.