php – 检查laravel中的朋友

前端之家收集整理的这篇文章主要介绍了php – 检查laravel中的朋友前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
如何检查,如果Auth:user()是当前$user的朋友?

这将放在配置文件上,以显示添加好友按钮或待处理请求等?我尝试过,与其他方法和条款的关系,但仍然没有成功.

请帮忙,非常感谢!!

要在这里继续,我需要这样的事情:

我需要这样的东西:

where user1_id = $user->id AND user2_id = Auth::user() AND is_friend = 1 
OR 
where user1_id = Auth::user() AND user2_id = $user->id AND is_friend = 1

所有这些,通过laravel雄辩?

我已经按照本教程
(Friendship system with Laravel : Many to Many relationship)关于如何建立双向关系,我有以下几点:

数据库

-users table-
id
username
age

-friends table-
id ->increments
user1_id ->reference->users.id
user2_id ->reference->users.id
is_accepted - return bool true or false,1 or 0

UserController.PHP

<?PHP

namespace App\Http\Controllers;
use Illuminate\Support\Facades\Auth;
use App\User;
use App\Friend;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use App\Http\Requests;
use App\Http\Controllers\Controller;

class UserController extends Controller
{
    /**
     * Display a listing of the resource.
     *
     * @return Response
     */
    public function getIndex($user)
    {

        $relation = User::with('friendsOfMine','friendOf','profileComments')
            ->where('username',$user);

        $user = User::findOrNew($user)
            ->where('username',$user)
            ->first();

        return view('users.profile')
            ->with('amigos',$relation)
            ->with('user',$user);
    }

型号User.PHP

//friendship i've started
function friendsOfMine()
{
return $this->belongsToMany('App\User','friends','user1_id','user2_id')
    ->wherePivot('is_friend','=',1) // to filter only accepted
    ->withPivot('is_friend'); // or to fetch accepted value
}

// friendship that I was invited to
function friendOf()
{
    return $this->belongsToMany('App\User','user2_id','user1_id')
    ->wherePivot('is_friend',1)
    ->withPivot('is_friend');
}

// accessor allowing you call $user->friends
    public function getFriendsAttribute()
{
    if ( ! array_key_exists('friends',$this->relations)) $this->loadFriends();

    return $this->getRelation('friends');
}

protected function loadFriends()
{
    if ( ! array_key_exists('friends',$this->relations))
    {
        $friends = $this->mergeFriends();

        $this->setRelation('friends',$friends);
    }
}

protected function mergeFriends()
{
    return $this->friendsOfMine->merge($this->friendOf);
}

Friend.PHP模型

<?PHP

namespace App;

use Illuminate\Database\Eloquent\Model;

class Friend extends Model
{
    protected $table = 'friends';
}

我试过了

$friendsAll = Friends::with('User')
            ->where('user1_id',$user)
            ->orWhere('user2_id',$user)
            ->first();

解决方法

试试这个:

$User = Auth::user();
$RequestedUser = User::find(Request::input('user_id'));

$Friendship = Friend::with('User')
              ->whereIn('user1_id',[$User->id,$RequestedUser->id])
              ->whereIn('user2_id',$RequestedUser->id])
              ->where('is_friend',1)
              ->first();

猜你在找的Laravel相关文章