I've read the documentation for Laravel 5.1 but I couldn't find (or understand) a way to get a child with a parent's id. I could do it with the query builder like this:
$child = \DB::table('children_table')->where('parent_id', $parent->id)->first();
But the problem with that is that it returns a stdClass, which I can't use later to update a belongsTo relationship. Can anyone help?
You can use query builder methods like where
on an Eloquent model
Since Eloquent models are query builders, you should review all of the methods available on the query builder. You may use any of these methods in your Eloquent queries.
https://laravel.com/docs/5.2/eloquent#retrieving-multiple-models
See the section titled Adding Additional Constraints .
Not sure if this is what you're getting at, but you could try this:
In your Parent class:
class Parent extends Model
{
public function children()
{
return $this->hasMany('App\Child');
}
In your Child class:
class Child extends Model
{
public function parent()
{
return $this->belongsTo('App\Parent');
}
Then, you should be able to do something like:
App\Parent::with('children')->find($id);
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.