简体   繁体   中英

Laravel Eloquent / Many to Many Relations gives error ( Array to string conversion )

I want to display all job posts that user have applied

Here is my Tables..

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

Ive tried belongsToMany() but gives error

mb_strpos(): Argument #1 ($haystack) must be of type string, array given

Post model Relation

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

Applies model

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

Lastly Controller

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

You have to pass pivot table name as second parameter to belongsToMany

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

If you see the implementation method.second parameter as table name

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM