如何在Eloquent - Laravel中轻松使用和访问元属性

时间:2022-10-16 08:06:12

I have a 'contents' table like this :

我有一个'内容'表,如下所示:

id title description  

I have another 'meta' table that stores extra fields for my contents :

我有另一个'meta'表,为我的内容存储额外的字段:

id content_id field_name field_vaue  

My question is How can I access MyModel->field_name as if it is in contents table I know I can use hasMany relation but it's not satisfy my needs.

我的问题是如何访问MyModel-> field_name,就好像它在内容表中我知道我可以使用hasMany关系,但它不能满足我的需要。

Thanks

2 个解决方案

#1


Use Metable extension from this package instead: https://github.com/jarektkaczyk/eloquence

请改用此软件包中的Metable扩展名:https://github.com/jarektkaczyk/eloquence

If you want to do it yourself, then check its source - a bit too long to show it here!

如果你想自己做,那么检查它的来源 - 有点太长了,不能在这里显示!

#2


Your can use:

你可以使用:

$new_table=DB::table('contents')
        ->join('meta', 'contents.id', '=', 'meta.content_id')
        ->get();

Now the $new_table will have the field_name and you can you it!

现在$ new_table将拥有field_name,你就可以了!

Hope it help!

希望它有所帮助!

#1


Use Metable extension from this package instead: https://github.com/jarektkaczyk/eloquence

请改用此软件包中的Metable扩展名:https://github.com/jarektkaczyk/eloquence

If you want to do it yourself, then check its source - a bit too long to show it here!

如果你想自己做,那么检查它的来源 - 有点太长了,不能在这里显示!

#2


Your can use:

你可以使用:

$new_table=DB::table('contents')
        ->join('meta', 'contents.id', '=', 'meta.content_id')
        ->get();

Now the $new_table will have the field_name and you can you it!

现在$ new_table将拥有field_name,你就可以了!

Hope it help!

希望它有所帮助!