Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
595 views
in Technique[技术] by (71.8m points)

php - 有没有一种方法可以使用自定义路由键来加载Laravel中雄辩的关系(Is there a way to get around using custom route key to load eloquent relationships in laravel)

I have two models Product and Images.

(我有两个模型Product和Images。)

I changed the route key name on the product model to use the slug field and i'm now unable to load the hasMany relationship with the Image Model

(我更改了产品模型上的路由键名称以使用slug字段,但现在无法加载具有图像模型的hasMany关系)

Here is the Product Model

(这是产品型号)

class Product extends Model
{
    protected array $with = ['images'];

    public function getKeyName()
    {
        return 'slug';
    }

    protected array $guarded = [];


    public function images() : HasMany
    {
        return $this->hasMany(Image::class, 'product_id');
    }
}

and the Image model

(和图像模型)


class Image extends Model
{
    protected array $guarded = [];

    public function image() : BelongsTo
    {
        return $this->belongsTo(Product::class);
    }
}

so when I try

(所以当我尝试)

    Product::first()->images

it just returns an empty collection but without overriding the getKeyName() method, everything works fine

(它只是返回一个空集合,但没有覆盖getKeyName()方法,所以一切正常)

  ask by emeka mamah translate from so

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

getKeyName() will get the primary key for the model.

(getKeyName()将获取模型的主键。)

it supports to return id , after you change it to slug , it will return slug

(它支持返回id ,将其更改为slug ,它将返回slug)

And hasMany Here's the source code ;

(和hasMany 这里的源代码 ;)

The third parameter LocalKey will use getKeyName() when it's empty.

(第三个参数LocalKey空时将使用getKeyName() 。)

If you still want to use hasMany, you need to pass the third parameter like this:

(如果仍然要使用hasMany,则需要像这样传递第三个参数:)

public function images()
{
    return $this->hasMany(Image::class, 'product_id', 'id');
}

This will convert the Eloquent query to database query, which will take the right local key products.id .

(这会将Eloquent查询转换为数据库查询,该查询将使用正确的本地密钥products.id 。)


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...