Friday, March 10, 2017

Laravel 5: Is there a way to list all values of a specific relation attribute from multiple models in a single query?

I have two models:

DropdownValue

use Illuminate\Database\Eloquent\Model;

class DropdownValue extends Model
{
    protected $table = "dropdown_values";
    public $timestamps = false;

    protected $fillable = [
        "field_id",
        "value",
    ];

    public function childValues()
    {
        return $this->belongsToMany("\\App\\Models\\ChildValue", "value_child", "parent_value_id", "child_value_id");
    }
}

and ChildValue model:

class ChildValue extends Model
{
    protected $table = "children_values";
    public $timestamps = false;

    protected $fillable = [
        "value"
    ];

    public function parentValue()
    {
        return $this->belongsToMany("\\App\\Models\\DropdownValue", "value_child", "child_value_id", "parent_value_id");
    }
}

I'm wondering if there is a way to get all the childValues values from multiple DropdownValue models at once using lists() method or using an alternative approach but without using any of the looping structures, just a one-line solution, if possible. Something like that:

$parent_values = DropdownValue::with("childValues")->get();
$child_values = $parent_values->lists("childValues.value")->all();


I'll consider any solution, even if it doesn't fit entirely in my requirements, so feel free to post your thoughts about this. Thank you in advance!



via Eseth

Advertisement