【问题标题】:Non-static method App\User::products() should not be called statically不应静态调用非静态方法 App\User::products()
【发布时间】:2020-11-15 18:02:26
【问题描述】:

我不知道为什么会出现此错误:

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 的产品表中。

【问题讨论】:

  • products 是用户模型的关系,它不是你可以使用User 模型调用的静态方法。

标签: php sql laravel orm frameworks


【解决方案1】:

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

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

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

@foreach($users as $user)

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

@endforeach

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-09-08
    • 1970-01-01
    • 2013-11-10
    • 1970-01-01
    • 1970-01-01
    • 2012-08-16
    相关资源
    最近更新 更多