質問

I have a pair of objects in laravel, pages and contents.

I have setup a relationship function, and include, which includes contents based on page_id.

I want to apply other conditions such as where deleted - 0, and where dates are within certain bounds, I know how to apply where conditions and set these field up.

What I can't fathom is how extra conditions can be applied as well as matching relationship fields.

Could anybody help me with this?

役に立ちましたか?

解決

Defining the relationship in the model is all you need to do to the model itself. However you can add a static function to the model to get the data with the information you need.

Page model methods examples:

class Page extends Eloquent {

    public function contents()    
    {
        return $this->has_many('Content');
    }

    // Return all content that has not been marked as
    // deleted in the database
    public static function with_contents($id)
    {
        return Page::find($id)->contents()
                              ->where_null('deleted')
                              ->get();
    }
}

This example assumes that the deleted field in the contents table is null unless it is deleted, in which case it will have any value.

To use you would simply use

$page = Page::with_contents('1');

You can create as many of these static helper methods as you like or add as many conditions to the one method as you like, then use your new static methods to retrieve your data.

他のヒント

I think this might be what you're looking for

http://doginthehat.com.au/2012/06/adding-conditions-to-relationships-in-laravel/

class User extends Eloquent {

    public function meta()
     {
          return $this->has_many('Meta','target_id')
                      ->where('target_type','=',$this->table());
     }

}
ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top