Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/php/287.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Php Laravel6.x将关系数据作为属性进行操作_Php_Laravel - Fatal编程技术网

Php Laravel6.x将关系数据作为属性进行操作

Php Laravel6.x将关系数据作为属性进行操作,php,laravel,Php,Laravel,在laravel中,是否可以使用关系创建自己的属性 例如: 客户与CustomerAddress有关系。现在,我想获取所有具有Relationships的客户,然后在customer上设置属性address。address字段将由customer\u address表的多列生成 customer\u address表中有street,state列,它们应该连接到客户模型上的address $customer=\App\customer::with(“customerAddress”)->get(

在laravel中,是否可以使用关系创建自己的属性

例如: 客户与CustomerAddress有关系。现在,我想获取所有具有Relationships的客户,然后在customer上设置属性
address
address
字段将由
customer\u address
表的多列生成

customer\u address
表中有
street
state
列,它们应该连接到客户模型上的
address

$customer=\App\customer::with(“customerAddress”)->get();
返回$customer->address;
>>街州

toArray()和toJSON()是否可能不忽略这些自定义属性?

确保您的模型中有正确的关系,然后定义一个方法返回自定义属性,然后将其添加到
$appends
数组中

客户

class Customer extends Model
{
    protected $appends = ['custom_attribute'];

    public function addresses()
    {
        return $this->hasMany(CustomerAddress::class, 'customer_id');
    }

    public function getCustomAttribute() {
        return 'some calculated data';
    }
}
客户地址

class CustomerAddress extends Model
{
    protected $appends = ['custom_attribute'];

    public function customer()
    {
        return $this->belongsTo(Customer::class, 'customer_id');
    }

    public function getCustomAttribute() {
        return 'some calculated data';
    }
}
请注意,属性名是skeel_case,而方法名在StudlyCase中,前缀是
get
(这使它最终成为camelCase)。方法名称和访问器名称必须匹配

现在,在控制器中,您可以获取所有客户及其地址

$customers = Customer::with("addresses:street,state")->get();
如果访问
$customers
,您将看到所有客户及其地址。现在可以使用custom属性返回自定义值

例如:

public function getCustomAttribute() {
      return "{$this->street} {$this->state}";
}

\App\Customer::with(“customerAddress”)->get()@MohammedRadwan这不是我的问题。我想通过模型获取集合中的自定义属性。然后只调用
toJSON()
,自定义属性应该是relationshipThx的两个值的相加,我唯一需要知道的是如何从那里访问关系。我现在很困惑:)你到底想做什么?编辑您的问题,使其更加具体和清晰。首先你说我需要一个自定义属性,正如我所解释的,现在你说你需要从那里访问关系。在哪里?共享您的模型代码和数据库结构以及关系类型(一对一、一对多或多对多)我希望
customer
成为属性
address
address
属性应使用
customer\u address
关系中的数据生成。我是否可以使用:
$customer->address
访问此地址,然后从
customer\u address
获取计算数据<代码>客户地址有例如
街道
。你现在明白了吗D客户和地址之间的关系类型是什么?是每个客户一个地址还是每个客户多个地址?一个客户可以有多个地址