简体   繁体   中英

Querying Models in Laravel

I would like to be able to write an eloquent query that I could pass in to this model function to return only categories that have stories published on $publishDate.

EG - This is what I desire but I am getting the following error 'Call to undefined method Illuminate\\Database\\Query\\Builder::stories()'

In my controller:

Category::orderBy('id', 'ASC')->stories($publishDate)->get();

And in my Model:

public function stories($publishDate)
{      
    return $this->hasMany('Workbench\Dailies\Story', 'category_id')
    ->orderBy('story_title', 'ASC')
    ->where('publish_date', $publishDate);
}

I am sure this is something very simple but I can not quite figure it out. Thanks in advance.

relation:

public function stories()
{      
    return $this->hasMany('Workbench\Dailies\Story', 'category_id');
}

then

// $publishedAt is some date you want

Category::whereHas('stories', function($query) use ($publishedAt) { 
    $query->where('published_at', '=', $publishedAt)->orderBy('story_title','asc'); 
})->orderBy('id','asc')->get();

I haven't found a way to do this in any similar way. The way I have found is similar to (in your context):

Category::join('stories', 'categories.id', '=', 'stories.category_id')->where('stories.publish_date', '=', $publishDate)->orderBy('id', 'ASC')->get();

Although, I prefer using DB::select with DB::raw to select the fitered IDs only then with the ORM I do Category::whereIn('id', <returned IDs>)->get() (in your context).

$sql = 'SELECT c.ID FROM categories c LEFT/INNER JOIN stories s ON (c.id = s.category_id) WHERE s.publish_date = ?';
$ids = DB::select(DB::raw($sql), array($publishDate));
// you can now iterate with array_walk, foreach, for, etc. the args to extract IDs from object rows
for($i = 0; $i < count($ids); $i++)
    $ids[$i] = (int) $ids[$i]->id;

$cats = Category::whereIn('id', $ids)->orderBy('id', 'ASC')->get();

The bad is that part is not so well documented. I was very surprised, because other ORMs allow such relation quering.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM