【问题标题】:Laravel Eloquent / Many to Many Relations gives error ( Array to string conversion )Laravel Eloquent / 多对多关系给出错误(数组到字符串的转换)
【发布时间】:2022-01-05 16:39:31
【问题描述】:

我想显示用户已申请的所有职位

这是我的表..

applies   ->  | users_id | posts_id |
posts     ->  | id       | (other posts cols ... )
user_info ->  | id       | (name col etc...)

我试过belongsToMany(),但报错

mb_strpos(): 参数 #1 ($haystack) 必须是字符串类型,给定数组

后模型关系

public function applies()
{
   return $this->belongsToMany(Applies::class ,'applies', 'users_id' , 'posts_id');
}

应用模型

   protected $table = 'applies';
    protected $primaryKey = ['user_id', 'id'];
    public $incrementing = false;
    protected $fillable = [
        'user_id',
        'posts_id'
    ];

最后的控制器

public function index()
{
    $infos = Info::where('user_id', Auth::id())->first();
    $apply = Post::find(2)->applies ;
    var_dump($apply);
}

【问题讨论】:

    标签: php laravel eloquent


    【解决方案1】:

    您必须将数据透视表名称作为第二个参数传递给belongsToMany

     return $this->belongsToMany(User::class ,'applies', 'users_id' , 'posts_id');
    

    如果看到实现方法.second参数为表名

      public function belongsToMany($related, $table = null, $foreignPivotKey = null, $relatedPivotKey = null,
                                      $parentKey = null, $relatedKey = null, $relation = null)
    

    【讨论】:

    • 哦,谢谢.. 我现在添加了表格,但这次给出了mb_strpos(): Argument #1 ($haystack) must be of type string, array given 错误
    • User::class not Applys::class for first param
    猜你喜欢
    • 2018-04-02
    • 1970-01-01
    • 2017-05-10
    • 1970-01-01
    • 2019-06-13
    • 2019-03-26
    • 2022-01-24
    • 1970-01-01
    • 2019-05-01
    相关资源
    最近更新 更多