简体   繁体   中英

How to modify Laravel model collection?

I have 2 database tables. The first table is the files that have a link (and other parameters) to a file on the server. The second table has a file_id column that stores the id of the line with the file in the files table. How can I make a join element from the table files on querying to model. Getting a collection and adding an image in a loop is not suitable. I need something like a function called when accessing a model (not a __construct ()), something as accessor, but for collection

You can eager load the relationship so it will have the file as part of the Model that contains file_id .

On the Model that has file_id , add a hasOne relationship for the File model:

public function file()
{
    return $this->hasOne(File::class);
}

https://laravel.com/docs/8.x/eloquent-relationships#one-to-one

You can define the inverse on the File model:

public function otherModel()
{
    return $this->belongsTo(OtherModel::class);
}

https://laravel.com/docs/8.x/eloquent-relationships#one-to-one-defining-the-inverse-of-the-relationship

This will allow you to eager load the File when you access the other model.

You can eager load as you go using the with() method:

$otherModel = OtherModel::with('file')->...

https://laravel.com/docs/8.x/eloquent-relationships#nested-eager-loading-morphto-relationships

Or eager load every time you access the other model by adding the $with to the model it self:

protected $with = ['file'];

https://laravel.com/docs/8.x/eloquent-relationships#eager-loading-by-default

--

You will then get the File as part of your other Model like so:

[
    'id' => 1,
    'file_id' => 4,
    'file' => [
        'id' => 11,
         ...,
    ],
    ...,
],

--

Also, as you have defined the inverse relationship, you can eager load the other model when you access a File using with() ;

$file = File::with('otherModel')->...

Or as shown above, eager load by default in the File model:

protected $with = ['otherModel'];

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