Pregunta

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?

¿Fue útil?

Solución

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.

Otros consejos

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());
     }

}
Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top