不应静态调用非静态方法app\user::products()

brtdzjyr  于 2021-07-29  发布在  Java
关注(0)|答案(1)|浏览(378)

我不知道为什么会出现这样的错误:

Non-static method App\User::products() should not be called statically

这是我的控制器方法:

public function create()
{
    $users = User::products('name', 'id');
    return view('products.create')->with('users', $users);
}

这是我的模型

<?php

namespace App;

use Illuminate\Notifications\Notifiable;
use Illuminate\Contracts\Auth\MustVerifyEmail;
use Illuminate\Foundation\Auth\User as Authenticatable;
use Spatie\Permission\Traits\HasRoles;
use Kyslik\ColumnSortable\Sortable;
use Illuminate\Database\Eloquent\Model;

class User extends Authenticatable
{
    use Notifiable;
    use HasRoles;
    use Sortable;
    /**
     * The attributes that are mass assignable.
     *
     * @var array
     */
    protected $fillable = [
        'name', 'email', 'password', 'surname', 'showname', 'business', 'NIP', 'PESEL', 'address', 'city', 'postalcode', 'phone', 'comments', 
    ];
    public $primaryKey = 'id';
    /**
     * The attributes that should be hidden for arrays.
     *
     * @var array
     */
    protected $hidden = [
        'password', 'remember_token',
    ];

    /**
     * The attributes that should be cast to native types.
     *
     * @var array
     */
    protected $casts = [
        'email_verified_at' => 'datetime',
    ];

    public $sortable = ['name',
                        'email',
                         'surname', 
                        'showname', 
                        'business',
                        'address',
                        'city',
                        'phone',
                        'role',
                       ];

        public function products()
    {
        return $this->hasMany('App\Product');
    }
        public function invoices()
    {
        return $this->hasMany('App\Invoice');
    }
}

你能帮助我吗?我试图做动态依赖下拉菜单在这个视图。要从视图中的下拉列表中获取用户名和id,然后将产品与用户连接,并使用用户id将数据保存到产品表中。

waxmsbnn

waxmsbnn1#

关系将在模型上被调用,因此必须从用户模型中获取它们。将控制器逻辑更改为只获取用户,而不是任何产品。

public function create()
{
    $users = User::all();
    return view('products.create')->with('users', $users);
}

因此,在创建下拉列表的blade文件中,循环用户,然后可以循环产品。

@foreach($users as $user)

    @foreach($user->products as $product) // fetch products
        // do your magic
    @endforeach

@endforeach

相关问题